Add or update an array element

I created an array like:

myarr: [ { name:'London', population:'7000000' }, { name:'Munich', population:'1000000' } ] 

At some point, I need to add several new elements to the array, but first I need to check if an element with the same name exists. If so, the value should be updated. If not, a new item must be created and added. If the value in the new element is zero and the element exists, it must be removed from the array.

+4
source share
2 answers

This should do the 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); 
+3
source

You can do it as follows:

 function myFunction(myarr, item) { var found = false; var i = 0; while (i < myarr.length) { if (myarr[i].name === item.name) { // Do the logic (delete or replace) found = true; break; } i++; } // Add the item if (!found) myarr.push(item); return myarr; } 
+2
source

Source: https://habr.com/ru/post/1500538/


All Articles