Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  76] [ 7]  / answers: 1 / hits: 46614  / 8 Years ago, thu, may 5, 2016, 12:00:00

I want to update (replace) the objects in my array with the objects in another array. Each object has the same structure. e.g.



var origArr = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: true},
{name: 'Kasich', isRunning: true}
];
var updatingArr = [
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}
];
// desired result:
NEWArr = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}
];


I've tried concat() & Underscore's _.uniq function, but it always dumps the newer object & returns, essentially, the original array.



Is there a way to overwrite (replace) origArr with the objects in updatingArr -- matching on the name property?


More From » arrays

 Answers
9

Using a double for loop and splice you can do it like so:



for(var i = 0, l = origArr.length; i < l; i++) {
for(var j = 0, ll = updatingArr.length; j < ll; j++) {
if(origArr[i].name === updatingArr[j].name) {
origArr.splice(i, 1, updatingArr[j]);
break;
}
}
}


Example here


[#62289] Tuesday, May 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
desiraeleandrah

Total Points: 202
Total Questions: 111
Total Answers: 115

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
;