简体   繁体   中英

Edit Object Item with Javascript

I am trying to edit data in an array based upon its id. Here is my array:

var myCollection = {
"data": [
{ "id":"1", "Name":"John Smiths", "AMT_STD":"1.99"},
{ "id":"2", "Name":"Carlsberg", "AMT_STD":"1.99"},
{ "id":"3", "Name":"Samuel Adams", "AMT_STD":"1.99"}
  ]};

What I would like to be able to do is create a function that will allow me to find id=1 within the array and then update the value of AMT_STD to 1.00.

From looking at other questions I have managed to add to the array and delete items but I have not yet figured out how to find and then edit and item.

I use the code below to add items:

function Add_Item() {
myCollection.data.push( { "id":"4", "Name":"Fosters", "AMT_STD":"1.99" } );
}

I use the code below to delete items:

function findAndRemove(array, property, value) {
$.each(array, function(index, result) {
if(result[property] == value) {
array.splice(index, 1);
}    
});

called by findAndRemove(myCollection.data, 'id', '1');

I have tried to edit the findAndRemove function as that method can find the item within the array however I cant figure out the syntax to edit the item within the index and was hoping someone could point me in the right direction.

You can go that way, and have a function to do so..

but if you can still change the format, consider having

var myCollection = {
  data: {
    1:{Name:"John Smiths", "AMT_STD":"1.99"},
    2:{Name:"Carlsberg", "AMT_STD":"1.99"},
    3:{Name:"Samuel Adams", "AMT_STD":"1.99"}
  }
}

insertion or record updates could be done like this:

myCollection.data[4]={Name:"Fosters", "AMT_STD":"1.99" }

updating a value:

myCollection.data[2]["AMT_STD"]="2.00"

retrieving data

myCollection.data[1];//the full record
myCollection.data[1].Name;//just the name
myCollection.data[1]["AMT_STD"];//similar to the previous but can use more complex keys/names

delete a record

delete myCollection.data[2];

this way no code to insert, search or delete is needed (using javascript object builtin habilities). You can use strings as ids (not restricted to numbers) and you gain advantage of fast index search that javascript have

hope it helps.

There are good guidelines in the other answers. However, if you really want to do it similar to the findAndRemove function, the most analogous way would be the create a function findAndReplace as follows which takes as additional arguments the property to be updated upon finding a match ("AMT_STD" in your case) and the value it should be updated to (1.00 in your case):

   function findAndReplace(array, property, value, replaceProperty, replaceValue) {
    $.each(array, function(index, result) {
        if (result[property] == value) {
            result[replaceProperty] = replaceValue;
        }
    });
   } 

Call it as follows:

findAndReplace(myCollection.data, 'id', '1', 'AMT_STD', 1.00);

As an additional sidenote, the findAndRemove function you have in your question actually will cause javascript errors in some browsers. You can't call the splice method in the middle of the ".each" function because jQuery will then try and run the function on one of the deleted objects in the array which then has an undefined value. The better way to do it is to save the index of the item to be deleted in a variable and then after .each has been executed run the splice function.

How about this prototype method?

Array.prototype.updateById = function(id, key, val) {
  // Loop the array - this refers to the array in this context
  for (var i = 0; i < this.length; i++) {
    if (this[i].id == id) {
      this[i][key] = val;
      return true;
    }
  }
  return false;
};

// Use it like this:
var updateSuccess = myCollection.data.updateById(1, "AMT_STD", "1.00");

// updateSuccess is now a boolean indicating whether the object was found and updated

By prototyping it, you can use the method with any array object that contains objects with an id property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM