javascriptarraysobjectnested-object

Modify array of the nested objects by its nested object's properties


I have the following structure in my array.

const data = [
  {
    name: 'Book_1',
    value: {
      eng: 'english_book_1',
      sp: 'spanish_book_1'
    }
  },
  {
    name: 'Book_2',
    value: {
      eng: 'english_book_2',
      sp: 'spanish_book_2'
    }
  }
];

And trying to get a structure like this:

[
  {
    eng: {
      Book_1: 'english_book_1',
      Book_2: 'english_book_2'
    }
  },
  {
    sp: {
      Book_1: 'spanish_book_1',
      Book_2: 'spanish_book_2'
    }
  }
];

So, the array should have language keys and nested book names with values in it. I tried a couple of things but even close.

const modified = [];
const object = {};
data.forEach(el => {
  Object.entries(el.value).forEach(([name, value]) => {
    if (object['name']) {
    }
    modified.push(object);
  });
});
```

Thanks.

Solution

  • You could reduce the array by taking an object for the language's objects.

    const
        data = [{ name: 'Book_1', value: { eng: 'english_book_1', sp: 'spanish_book_1' } }, { name: 'Book_2', value: { eng: 'english_book_2', sp: 'spanish_book_2' } }],
        result = Object.values(data.reduce((r, { name, value }) => {
            Object
                .entries(value)
                .forEach(([k, v]) => (r[k] ??= { [k]: {} })[k][name] = v);
            return r;
        }, {}));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }