1

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.
mplungjan
  • 169,008
  • 28
  • 173
  • 236
zana10
  • 113
  • 1
  • 8

1 Answers1

2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Hallo, schon lange nicht gesehen. [Dieser hat mich verwirrt](https://stackoverflow.com/questions/74158072/array-of-object-arrays-filtering-does-not-retain-the-changes-outside-foreach) schau mal bitte? – mplungjan Oct 22 '22 at 05:38