带有对象的转置JavaScript数组[处于保留状态]

问题描述 投票:-7回答:1

我具有此形状的数组宽度:

[ 
{author: "Author 1", label: "label1", photos: 251},
{author: "Author 1", label: "label2", photos: 32},
{author: "Author 2", label: "label1", photos: 43},
{author: "Author 2", label: "label2", photos: 78},
...
]

我想将其转换为:

[
{author: "Author 1", label1: 251, label2: 32},
{author: "Author 2", label1: 43, label2: 78},
...
]

我尝试使用Lodash,但做得不好。我知道我必须按作者分组,然后再将标签值作为键转置,将照片值作为其值。但是我不怎么做。

javascript arrays lodash transform
1个回答
-1
投票

您可以在作者姓名和想要的对象之间建立映射:

const data = [ 
  {author: "Author 1", label: "label1", photos: 251},
  {author: "Author 1", label: "label2", photos: 32},
  {author: "Author 2", label: "label1", photos: 43},
  {author: "Author 2", label: "label2", photos: 78},
];

const objectMap = {};

data.forEach((item) => {
  const object = objectMap[item.author] || { author: item.author };
  object[item.label] = item.photos;
  objectMap[item.author] = object;
});

const objects = Object.values(objectMap);

console.log(objects);
© www.soinside.com 2019 - 2024. All rights reserved.