Search code examples
javascriptarraysobject-literal

How do I apply changes to a data object within a JavaScript array?


If I have the following:

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

How do I update the value of the object using JavaScript? I have been trying the following:

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

 }

So I tried to pop the dataContainer[i] and push the thisData back on but this didn't work. Unless I'm doing it incorrectly? What should I be doing here? I appreciate any help.


Solution

  • 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);
    

    I've added a fiddle that prints out the result as well: http://jsfiddle.net/4UH9e/