gpt4 book ai didi

javascript - 如何检查对象数组中是否存在对象并更新数量?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:45 27 4
gpt4 key购买 nike

我有一个数组 objArray。我想创建一个函数,以便它检查是否有另一个对象具有相同的 name 键。如果存在,它将在 qty 键中添加 +1。如果该对象不存在,它会将新对象推送到数组。

var objArray = [
{"name":"bike","color":"blue","qty":2},
{"name":"boat","color":"pink", "qty":1},
];

var carObj = {"name":"car","color":"red","qty":1};
var bikeObj = {"name":"bike","color":"blue","qty":1};

function checkAndAdd (obj) {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].name === obj.name) {
objArray[i].qty++;
break;
}
else {
objArray.push(obj);
}
};
}

checkAndAdd(carObj);

console.log(objArray);

checkAndAdd(bikeObj);

console.log(objArray);

checkAndAdd(carObj); 之后

console.log(objArray);

应该给

[
{"name":"car","color":"red", "qty":1},
{"name":"bike","color":"blue","qty":2},
{"name":"boat","color":"pink", "qty":1},
]

然后 checkAndAdd(bikeObj);

console.log(objArray);

应该给

[
{"name":"car","color":"red", "qty":1},
{"name":"bike","color":"blue","qty":3},
{"name":"boat","color":"pink", "qty":1},
]

提前致谢!

最佳答案

需要检查所有的对象,如果找到一个需要增加数量的项目就退出函数。

如果没有找到推送对象。

var objArray = [{ name: "bike", color: "blue", qty: 2 }, { name: "boat", color: "pink", qty: 1 }],
carObj = { name: "car", color: "red", qty: 1 },
bikeObj = { name: "bike", color: "blue", qty: 1 };

function checkAndAdd (obj) {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].name === obj.name) {
objArray[i].qty++;
return; // exit loop and function
}
}
objArray.push(obj);
}

checkAndAdd(carObj);
console.log(objArray);

checkAndAdd(bikeObj);
console.log(objArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何检查对象数组中是否存在对象并更新数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49780953/

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