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 = [
const origArr = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: true},
{name: 'Kasich', isRunning: true}
];
const updatingArr = [
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}
];
let hash = {};
for(let i of origArr.concat(updatingArr)) {
if(!hash[i]) {
hash[i.name] = i;
}
}
let newArr = [];
for(let i in hash) {
newArr.push(hash[i])
}
console.log(newArr);
You can use a hash which gives the index by name, and Object.assign
to update.
var hash = origArr.reduce(function(hash, obj, index) {
hash[obj.name] = index;
return hash;
}, Object.create(null));
for(var obj of updatingArr) {
Object.assign(origArr[hash[obj.name]], obj);
}
Try this approach with ES-6 Set Data Structure:
const result = [...new Set([...origArr, ...updatingArr])]
I came here looking for exactly this, saw @Gruff Bunny 's technique and wondered if 'lodash' wouldn't perhaps be a superior option even to 'underscore'?
Lo and behold :
let result = _.unionBy(updatingArr, origArr, 'name');
You can give this a try.
var origArr = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: true},
{name: 'Kasich', isRunning: true}
];
var updatingArr = [
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}
];
var origLength = origArr.length;
var updatingLength = updatingArr.length;
//Traverse the original array and replace only if the second array also has the same value
for(i = origLength-1; i >= 0; i--) {
for(j = updatingLength -1; j >= 0; j--) {
if(origArr[i].name === updatingArr[j].name) {
origArr[i] = updatingArr[j];
}
}
}
console.log(origArr);
You could use Array#map in combination with Array#reduce
var origArr = [{ name: 'Trump', isRunning: true }, { name: 'Cruz', isRunning: true }, { name: 'Kasich', isRunning: true }],
updatingArr = [{ name: 'Cruz', isRunning: false }, { name: 'Kasich', isRunning: false }],
NEWArr = origArr.map(function (a) {
return this[a.name] || a;
}, updatingArr.reduce(function (r, a) {
r[a.name] = a;
return r;
}, Object.create(null)));
document.write('<pre>' + JSON.stringify(NEWArr, 0, 4) + '</pre>');