如何基于对象的ID将密钥对值添加到数组中的每个对象(该数组是ajax调用的响应)?
这是我到目前为止尝试过的,但是没有给我定义。
self.initialData = response.data.projectRequests.forEach(projectRequest => {
Object.assign(projectRequest, "/view-project-team/" + projectRequest.id);
});
答案 0 :(得分:0)
您可以通过以下操作以不变的方式添加键值对:
var pr = [
{
id: 1,
data: "data"
},
{
id: 2,
data: "data"
}
]
console.log(pr);
var newPr = [];
pr.forEach(projectRequest => {
newPr.push(Object.assign({}, projectRequest, {url: "/view-project-team/" + projectRequest.id}));
});
console.log(newPr);
基本上,您做错的只是使用Object.assign()。它采用对象宽度应添加的值。您也可以这样做:
var pr = [
{
id: 1,
data: "data"
},
{
id: 2,
data: "data"
}
]
pr.forEach(projectRequest => {
Object.assign(projectRequest, {url: "/view-project-team/" + projectRequest.id});
});
要添加新的键值对(在本例中为“ url”)。