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.
2
  • 1
    btw, why an array for the language and for books object? Commented Aug 27, 2021 at 18:07
  • Idk, it's predefined, received data. Commented Aug 27, 2021 at 18:10

1 Answer 1

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; }

Sign up to request clarification or add additional context in comments.

1 Comment

Hallo, schon lange nicht gesehen. Dieser hat mich verwirrt schau mal bitte?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.