3 回答
TA贡献1811条经验 获得超5个赞
你很接近。使用Array#reduce是正确的方法。您只需要更改ac[clientId] = rest为您想要的结构:
const obj = {
"id": "98765",
"things": [{
"clientId": "123456",
"val": "file1",
"cmpId": "54353"
},
{
"clientId": "1234",
"val": "file2",
"cmpId": "3453"
},
{
"clientId": "1234",
"val": "file3",
"cmpId": "5433"
}
]
};
obj.things = obj.things.reduce( ( res, { clientId, cmpId, ...rest } ) => {
res[clientId] = { ...res[clientId], [cmpId]: rest };
return res;
}, { } );
console.log( obj );
TA贡献1859条经验 获得超6个赞
你快到了,你还需要获取cmpId然后检查是否已经有一个对象clientId,这里是一个例子:
const input = {
"id": "98765",
"things": [{
"clientId": "123456",
"val": "file1",
"cmpId": "54353"
},
{
"clientId": "1234",
"val": "file2",
"cmpId": "3453"
},
{
"clientId": "1234",
"val": "file3",
"cmpId": "5433"
}
]
};
input.things = input.things.reduce((a, {
clientId,
cmpId,
...rest
}) => {
if (a[clientId]) {
a[clientId][cmpId] = rest;
} else {
a[clientId] = {
[cmpId]: rest
};
}
return a;
}, {});
console.log(input);
添加回答
举报