0

如果我有以下情况:

var dataContainer = [
                       { id : 1, value : 5, qty : 73, orders: 7 },
                       { id : 2, value : 6.15, qty : 212, orders: 49},
                       { id : 3, value : 12.11, qty : 29, orders : 6} 
                    ];

如何使用 JavaScript 更新对象的值?我一直在尝试以下方法:

function UpdateValues(passedId) {
    var thisData = {};
    for ( var i = 0; i < dataContainer.length; i++ ) {
      thisData = dataContainer[i];
       if (thisData.id == passedId) {
           // I am updating the values in thisData 
       }
     }
     // Not sure what to do here in order to get thisData values back into dataContainer

 }

所以我试图弹出dataContainer[i]并推thisData回,但这没有用。除非我做错了?我应该在这里做什么?我很感激任何帮助。

4

2 回答 2

1
function UpdateValues(passedId, prop, newValue) {
    var thisData = {};
    for ( var i = 0; i < dataContainer.length; i++ ) {
        thisData = dataContainer[i];
        if (thisData.id == passedId) {
            thisData[prop] = newValue;
        }
    }
}

//Change qty to 99999 for object with index of 1
UpdateValues(1, "qty", 99999);

我还添加了一个打印结果的小提琴:http: //jsfiddle.net/4UH9e/

于 2013-07-08T19:49:19.430 回答
1
function UpdateValues(passedId) {
    var thisData = {};
    for ( var i = 0; i < dataContainer.length; i++ ) {
        var data = dataContainer[i];
        for (i in data) {
            thisData[i] = data[i];
        }
        if (thisData.id == passedId) {
           //Update the values in thisData. 
        }
    }
    //You still have the original data in dataContainer
}
于 2013-07-08T19:58:53.373 回答