在JavaScript中插入或更新对象

时间:2016-01-01 15:24:38

标签: javascript jquery object

我正在尝试使用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;
        }
    });
}

但我得到了:

  

未捕获的TypeError:无法设置未定义的属性“数量”

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

4 个答案:

答案 0 :(得分:3)

更改

model.i.quantity = quantity;

model[i].quantity = quantity;

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

.i将在对象'i'内搜索密钥model,而在model[i]中,i的值将首先被替换,然后密钥将被替换在model对象中搜索。

<强>更新

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

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;
}

答案 1 :(得分:0)

我认为问题是在空模型array.due中,该模型[i]显示为undefined。因此,它抛出了以下错误。

无法设置未定义的属性“数量”

答案 2 :(得分:0)

如果您的i始终为整数,则应使用model[parseInt(i)].quantity = quantity

如果不是,则需要定义模型var model = {},而不是var model = []

答案 3 :(得分:0)

我认为你应该根据产品ID,大小和颜色创建动态数组,所以我缩短了你的代码,

$(document).ready(function(){
     var model = [];
     var formattedModel=[];


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

    if(!model.hasOwnProperty(product_id)) model[product_id]=[];
    if(!model[product_id].hasOwnProperty(size_id)) model[product_id][size_id] = [];

    model[product_id][size_id][colour_id]= quantity;
   console.log(model);
   //iterate through keys
   for (var p in model){
        var formattedModel=[];
        if (model.hasOwnProperty(p)) {

         for(var s in model[p])
         if (model[p].hasOwnProperty(s)) {
            for(var c in model[p][s])
            {
             if(model[p][s].hasOwnProperty(c)) {
              formattedModel.push({
              "product_id":p,
              "size_id":s,
              "colour_id":c,
              "quantity":model[p][s][c]
              });
             }
            }
         }
    }
    }

    console.log(formattedModel); // your model structure


    });


 });

它将添加产品或更新产品,然后您可以轻松地遍历数组。

工作小提琴https://jsfiddle.net/kodedsoft/hvdL4da5/1/