我有这样的数据响应
{
"data": {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [
{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
}
}
然后我想将颜色推送到项目内
预期:项目的每个索引有三 (3) 个变量
items: [
{
label: phone,
value: 23.00,
color: #3498db
}
]
我尝试使用推送和连接,但出现错误“无法读取未定义的属性‘数据’”
这是我的代码
generaliseData(dashboardC) {
let genData = Object.assign({}, dashboardC)
if (genData.product.items.length > 0) {
for (let i of genData.product.items) {
i.value = parseInt(i.value)
for (let j of genData.product.colors) {
i = i.push(j)
}
}
console.log(genData)
}
}
最佳答案
您可以使用map要迭代列表,期望颜色的长度等于项目的长度
const response = {
"data": {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [
{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
}
};
function addColorToItem(response) {
const product = response.data.product;
const colors = product.colors;
const items = product.items;
return items.map((item, index) => {
item.color = colors[index];
return item;
})
}
console.log(addColorToItem(response));
关于javascript - 如何将数组值推送到另一个数组对象值javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53078635/