我希望能够分配一个名为likeTotalForComment
的新嵌套属性,如下所示:
{
comment: [
{
likeTotalForComment:
}
]
}
这是我目前写的:
commentLikes = data.map(
(v,i) => {
return( v.comment.map(
(c, ci) => {
newValue = sumFunc(data[i].comment[ci].like, 'value')
return data[i].comment[ci] = {likeTotalForComment: newValue}
}
)
)
}
)
console.log(commentLikes)
退货给了我
[[{likeTotalForComment: 2}, {likeTotalForComment: 4}]]
不是整个对象都具有新的嵌套属性,这正是我想要的
以下是一些示例数据:https://codepen.io/schoenbl/pen/gVgJLm?editors=0010
答案 0 :(得分:0)
使用Object.spread将新属性合并到旧对象
data = data.map(v => {
return {...v, comment: v.comment.map(c => {
let newValue = sumFunc(c.like, 'value');
return { ...c, likeTotalForComment: newValue };
})}
});
或只是将新属性分配给旧对象
data.forEach(v => {
data.comment.forEach((comment) => {
let newValue = sumFunc(c.like, 'value');
comment['likeTotalForComment'] = newValue
});
})