javascript - Add or update an array element -
i created array like:
myarr: [ { name:'london', population:'7000000' }, { name:'munich', population:'1000000' } ]
at point need add new elements array, first need check if element same name exists. if yes, value must updated. if no, new element must created , added. if value in new element equals 0 , element exists, must removed array.
this should trick http://jsfiddle.net/tcwqv/
var arr = [ { name:'london', population:'7000000' }, { name:'munich', population:'1000000' } ] var addnewelement = function(arr, newelement) { var found = false; for(var i=0; element=arr[i]; i++) { if(element.name == newelement.name) { found = true; if(newelement.population === 0) { arr[i] = false; } else { arr[i] = newelement; } } } if(found === false) { arr.push(newelement); } // removing elements var newarr = []; for(var i=0; element=arr[i]; i++) { if(element !== false) newarr.push(element); } return newarr; } arr = addnewelement(arr, {name: 'paris', population: '30000000'}); console.log(arr); arr = addnewelement(arr, {name: 'paris', population: '60000000'}); console.log(arr); arr = addnewelement(arr, {name: 'paris', population: 0}); console.log(arr);
Comments
Post a Comment