Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  30] [ 7]  / answers: 1 / hits: 19686  / 12 Years ago, sat, april 21, 2012, 12:00:00

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.


More From » javascript

 Answers
41

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.


[#86090] Friday, April 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shamya

Total Points: 38
Total Questions: 101
Total Answers: 96

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;