将多个对象映射到一个数组中
Map multiple objects into one array
我有一个已解析的 json 数组:
parsedJson = JSON.parse(comments);
const reformattedArray = parsedJson.map(({username, rating}) => ({[username]: rating}));
[{…}, {…}, {…}, {…}, {…}]
[{First username: 5}, {Second username: 4}, {Third username: 3}, {Fourth username: 2}, {Fifth username: 1}]
但是我的数组怎么可能像这样:
{…,…,…,…,…}
{First username: 5, Second username: 4, Third username: 3, Fourth username: 2, Fifth username: 1}
是否可以让这个数组看起来像这样?
您可以使用 Array.reduce
轻松实现此目的:
const data = [{FirstUsername: 5}, {SecondUsername: 4}, {ThirdUsername: 3}, {FourthUsername: 2}, {FifthUsername: 1}]
const oneObject = data.reduce((total, current) => {
const keyName = Object.keys(current)[0]
total[keyName] = current[keyName]
return total
}, {})
console.log(oneObject)
我有一个已解析的 json 数组:
parsedJson = JSON.parse(comments);
const reformattedArray = parsedJson.map(({username, rating}) => ({[username]: rating}));
[{…}, {…}, {…}, {…}, {…}]
[{First username: 5}, {Second username: 4}, {Third username: 3}, {Fourth username: 2}, {Fifth username: 1}]
但是我的数组怎么可能像这样:
{…,…,…,…,…}
{First username: 5, Second username: 4, Third username: 3, Fourth username: 2, Fifth username: 1}
是否可以让这个数组看起来像这样?
您可以使用 Array.reduce
轻松实现此目的:
const data = [{FirstUsername: 5}, {SecondUsername: 4}, {ThirdUsername: 3}, {FourthUsername: 2}, {FifthUsername: 1}]
const oneObject = data.reduce((total, current) => {
const keyName = Object.keys(current)[0]
total[keyName] = current[keyName]
return total
}, {})
console.log(oneObject)