gpt4 book ai didi

javascript - 如何更新数组对象的数组特定属性

转载 作者:行者123 更新时间:2023-12-01 02:30:45 26 4
gpt4 key购买 nike

我想检查一个数组并找到包含某个东西的数组

我有一个包含这些值的购物车数组

  {id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"}

{id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"}

{id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "3"}

{id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "1"}

{id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "1"}

每个对象代表一个产品我真正想做的是防止 id 重复,因此如果 id 相同,我想合并数量。所以在我添加这种格式的新产品对象之前

{id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "7"}

我想检查cartarray中是否有类似的productid

var arrayLength = cartarry.length;
for (var i = 0; i < arrayLength; i++) {
if (cartarry[i] == product.id ){
console.log("we got a match")
var updatedquantity = quantity + parseInt(product.quantity)
}
}

我尝试了几种不同的方法但没有成功。如何找到匹配的 ID 并更新数量?我希望我的描述很清楚

最佳答案

要按您要使用的 ID 合并您的产品数量 Array.prototype.reduce :

let data = [
{id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"},
{id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"},
{id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "3"},
{id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "1"},
{id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "1"}
];

data = data.reduce((acc, item) => {
const foundItem = acc.find(_item => _item.id === item.id);
if(foundItem) {
foundItem.quantity = Number(item.quantity) + Number(foundItem.quantity) + '';
}
else {
acc.push(item);
}
return acc;
}, []);

console.log(data);

//0: {id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "2"}
//1: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "5"}

UPD。在reduce方法的帮助下,我们希望获得原始数据数组的处理副本。输出数组被形成为 acc 累加器值,它最初是一个空数组(这是由 reduce 的最后一个参数调节的:[])。初始数据集中的每个项目都被单独视为回调中的 item 局部变量,并且我们根据当前的 item 更改 acc内容。我们试图通过 id 在当前 acc 数组中查找当前 item 以合并数量。否则,如果当前 item 对于当前 acc 数组是唯一的,我们会将当前 item 推送到 acc

关于javascript - 如何更新数组对象的数组特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48331334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com