我有两个名称分别为 actutalpricesarray 和 modfiedpricesarray 的数组。
var actutalpricesarray =
[
{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
]
var modfiedpricesarray =
[
{"name":"apple","price":20},
{"name":"orange","price":30},
{"name":"strawberry","price":40}
]
我想为 actutalpricesarray 分配价格值 modfiedpricesarray ,以便modfiedpricesarray的输出看起来像
[{"name":"apple","price":100},{"name":"orange","price":200},{"name":"strawberry","price":40}]
以这种方式尝试
for(var i=0;i<modfiedpricesarray.length;i++)
{
var fruitnamemodfiedprice = modfiedpricesarray[i].name;
for(var j=0;j<actutalpricesarray.length;j++)
{
var fruitnameactualprice = actutalpricesarray[j];
if(fruitnamemodfiedprice==fruitnameactualprice)
modfiedpricesarray[i].price = actutalpricesarray[j].price;
}
}
console.log(JSON.stringify(modfiedpricesarray))
});
https://jsfiddle.net/o2gxgz9r/55230/
modfiedpricesarray的期望输出应为
[
{"name":"apple","price":100},
{"name":"orange","price":200},
{"name":"strawberry","price":40}
]
答案 0 :(得分:0)
这是您可以做的。我使用findIndex获取所需水果的索引,然后更新价格。还要检查我的codepen
var actutalpricesarray =[
{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
]
var modfiedpricesarray = [
{"name":"apple","price":20},
{"name":"orange","price":30},
{"name":"strawberry","price":40}
]
modfiedpricesarray.forEach((item,i) => {
var fruitnamemodfiedprice = item.name;
let index = actutalpricesarray.findIndex(x => x.name === fruitnamemodfiedprice);
if(index !== -1){
modfiedpricesarray[i].price = actutalpricesarray[index].price
}
})
console.log(JSON.stringify(modfiedpricesarray))
答案 1 :(得分:0)
您可以直接过滤数组,然后相应地更新值。您可以在下面进行测试。
var actutalpricesarray = [{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
];
var modfiedpricesarray = [{
"name": "apple",
"price": 20
},
{
"name": "orange",
"price": 30
},
{
"name": "strawberry",
"price": 40
}
]
actutalpricesarray.forEach((data) => {
modfiedpricesarray.filter((d) => d.name == data.name).forEach((d) => d.price = data.price);
});
console.log(modfiedpricesarray);