通过嵌套对象的属性修改嵌套对象的数组

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

我的数组中有以下结构。

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

并试图获得这样的结构:

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

因此,该数组应该包含语言键和嵌套的书名,其中包含值。 我尝试了几件事,但还是很接近。

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

Thanks.

您可以通过为语言的对象取一个对象来减少数组。

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