我有以下json:
click: false
image: "xxxx"
items: Array(4)
0:
click: false
image: "xxxx/chapter.png"
items: Array(12)
0:
click: true
courseID: 1
coverImage:"xxxxx"
duration: "(2':20)"
image: "xxxx/chapter.png"
pdfLinkIos:"xxxxx"
title: "Motion title"
videoLink: "xxxx"
_internalId: "MV6ZgJ_BxxeD"
,我想添加一个使用Async函数计算的元素。计算应针对具有“ click:true”的级别执行。我可以成功解析该函数,甚至可以正确计算它。 这是我的代码:
parseValues=(obj)=> {
for(var k in obj) {
if(obj[k] instanceof Object) {
this.parseValues(obj[k]);
} else {
console.log("[coverRnder] all", k, );
if(obj["click"]){
return this.accumulateRating(obj).then(rating => {
obj.push(rate: rating);
});
//obj[k].push("");
}
}
}
};
async accumulateRating(node) {
return;
}
我唯一的问题是我不知道如何将计算的元素添加到原始json的适当级别。 (this.state.courseContent)。
实际上,我需要在原始json中将accumulateRating
的输出显示为rate标题,如下所示:
click: false
image: "xxxx"
items: Array(4)
0:
click: false
image: "xxx"
items: Array(12)
0:
click: true
courseID: 1
coverImage:"xxxxxx"
duration: "(2':20)"
image: "xxxx"
pdfLinkIos:"xxxxxx"
title: "Motion title"
videoLink: "xxxx"
_internalId: "MV6ZgJ_BxxeD"
rate: 3.5
你能帮我吗?
答案 0 :(得分:1)
push()
适用于数组而不是对象。要将键/值对添加到对象,只需定义它即可。
return this.accumulateRating(obj).then(rating => {
obj.rate = rating;
//obj["rate"] = rating; also works
});