gpt4 book ai didi

javascript - 在 JavaScript 中插入或更新对象

转载 作者:行者123 更新时间:2023-11-28 18:50:29 25 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中构建一个对象,但根据产品 ID 是否已存在来更新或创建属性。我有:

var model = [];

$('.glyphicon-plus').click(function() {
var product_id = $('#productSelect').val();
var size_id = $('#sizeSelect').val();
var colour_id = $('#colourSelect').val();
var quantity = $('#quantity').val();
if (i = subFilter(model, "product_id", product_id) !== false) {
if (i = subFilter(model, "size_id", size_id) !== false) {
if (i = subFilter(model, "colour_id", colour_id) !== false) {
console.log(model);
model.i.quantity = quantity;
}
}
}
model.push({
product_id: product_id,
size_id: size_id,
colour_id: colour_id,
quantity: quantity
});
subFilter(model, "product_id", product_id);
console.log(model)
});

function subFilter(object, paramName, paramValue) {
$.each(object, function(i, v) {
if (v[paramName] == paramValue) {
return i;
}
});
}

但我得到:

Uncaught TypeError: Cannot set property 'quantity' of undefined

如何正确构建此对象,插入新的“记录”或更新该对象(如果已存在)?

最佳答案

改变

model.i.quantity = quantity;

model[i].quantity = quantity;

要访问对象的动态属性,请使用数组表示法。

.i 将在对象 model 中搜索键 'i',而在 model[i] 中> 首先替换i的值,然后在model对象中搜索key。

<小时/>

更新:

问题中的代码包含许多错误。尝试以下代码。

var model = [];

$('.glyphicon-plus').click(function () {
var product_id = $('#productSelect').val(),
size_id = $('#sizeSelect').val(),
colour_id = $('#colourSelect').val(),
quantity = $('#quantity').val();

// Get index of the element where all the fields matches
var index = getObjectIndex(model, product_id, size_id, colour_id);

// If object found in the array
if(index !== false) {
// Update the quantity in the same element
model[index].quantity = quantity;
} else {
// Add the element in the array
model.push({
product_id: product_id,
size_id: size_id,
colour_id: colour_id,
quantity: quantity
});
}
});

// Currently the function is Static, but it can be changed to dynamic
// by using nested loop and a flag to store the match status
function getObjectIndex(arr, product_id, size_id, colour_id) {
// Loop over array to find the matching element/object
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
if(obj.product_id === product_id && obj.size_id === size_id && obj.colour_id === colour_id) {
// When all key-value matches return the array index
return i;
}
}

// When no match found, return false
return false;
}

关于javascript - 在 JavaScript 中插入或更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557391/

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