gpt4 book ai didi

jquery - 在对象中查找 json 元素并将其删除

转载 作者:行者123 更新时间:2023-12-01 04:49:21 25 4
gpt4 key购买 nike

使用 jquery,我将如何查找 JSON 对象的索引。

下面是创建的内容:

[{"itemid":3,"itemName":"Some text here","itemPrice":"£2.40"},{"itemid":3,"itemName":"Some text here","itemPrice":"£2.40"},{"itemid":2,"itemName":"Some text here","itemPrice":"£2.40"}]

Here is how it translates in console:

[Object, Object, Object]0: ObjectitemName: "Some text here"itemPrice: "£2.40"itemid: 3__proto__: Object1: ObjectitemName: "Some text here"itemPrice: "£2.40"itemid: 3__proto__: Object2: ObjectitemName: "Some text here"itemPrice: "£2.40"itemid: 2__proto__: Objectlength: 3__proto__: Array[0]

If i wanted to look through the string by searching for the itemid as the value to find, and then go back and remove it from the string using splice, what would the code look like. I keep getting odd errors.

Here is the code i have:

This creates the json string: var item = {"itemid" : itemId, "itemName" : itemName, "itemPrice" : itemPrice};

cOrder.push(item);
localStorage.setItem('cOrder', JSON.stringify(cOrder));

在这里,我搜索字符串以获取要删除的正确元素:

var itemid = ($(this).text());
console.log(cOrder);
$.each(cOrder, function(key, value) {
if(value.itemid == itemid) {
// Here i need to get the index of the object //
console.log(Object.keys(cOrder).indexOf(this));
}
});

使用上述内容作为工作示例。如果我想删除 itemid 3,我需要删除对象索引 1(1:对象)

如何获取索引 1,然后将其从字符串中删除?

提前致谢

最佳答案

对于数组,您不能在循环中从数组的开头开始并删除项目...如果您这样做,循环计数器和索引将相互脱离。您可能需要创建第二个数组并在循环期间将有效项目添加到辅助数组中。

与 ID 匹配的项目:

var validItems = [];
$.each(cOrder, function(key, value) {
if(value.itemid == itemid) {
validItems.push(value);
}
});

项目与 ID 不匹配:

var validItems = [];
$.each(cOrder, function(key, value) {
if(value.itemid != itemid) {
validItems.push(value);
}
});

或者两者:

var validItems = [];
var invalidItems = [];
$.each(cOrder, function(key, value) {
if(value.itemid == itemid)
validItems.push(value);
else
invalidItems.push(value);
});

更新

这可能会帮助您解决数量问题。您必须向对象添加一个 itemQuantity 属性来支持这一点。使用该属性,您可以创建如下函数:

//quantity can be positive or negative
function adjustItemQuantity(itemId, quantity, remove) {
//if no quantity, or quantity==0, and not remove then nothing to do here
if (!quantity && !remove) return;

//create the temporary array
var validItems = [];

$.each(cOrder, function(key, value) {
if(value.itemid == itemId) {
var newQuantity = value.itemQuantity + quantity;

//remove if quantity 0 or less
if (newQuantity > 0 && !remove)
validItems.push(value);
} else {
//add the other, non-matching items to the array
validItems.push(value);
}
});

//set the main array to the new result
cOrder = validItems;
}

关于jquery - 在对象中查找 json 元素并将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23395911/

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