DotNetLearner DotNetLearner - 25 days ago 6
jQuery Question

jquery update property in an array from another array

I want to update a property in an array from another array by matching a field by using jquery.

objArray = [ { Id: 1, Val: 'A'}, { Id: 3, Val: 'B'}, { Id: 5, Val: 'C'} ];


After doing some processing, I am getting an array like this.

objnewArray = [ { Id: 1, Value: 'AA'}, { Id: 3, Value: 'BB'}, { Id: 5, Value: 'CC'} ];


Now I want to update objArray Val field to objnewArray's value field so the result is like this

objArray = [ { Id: 1, Val: 'AA'}, { Id: 3, Val: 'BB'}, { Id: 5, Val: 'CC'} ];


Is there any other way other than looping both the arrays ,matching the Id and updating the Val property?

Answer

You could use a hash table and loop the target first and the the new object for assigning to the old object.

var objArray = [{ Id: 1, Val: 'A' }, { Id: 3, Val: 'B' }, { Id: 5, Val: 'C' }],
    objnewArray = [{ Id: 1, Value: 'AA', extra: 42 }, { Id: 3, Value: 'BB' }, { Id: 5, Value: 'CC' }],
    hash = Object.create(null);

objArray.forEach(function (a) {
    hash[a.id] = a;
});

objnewArray.forEach(function (a) {
    Object.keys(a).forEach(function (k) {
        hash[a.id][k] = a[k];
    });
});

console.log(objnewArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6 with Map

var objArray = [{ Id: 1, Val: 'A' }, { Id: 3, Val: 'B' }, { Id: 5, Val: 'C' }],
    objnewArray = [{ Id: 1, Value: 'AA', extra: 42 }, { Id: 3, Value: 'BB' }, { Id: 5, Value: 'CC' }],
    hash = new Map;

objArray.forEach(a => hash.set(a.id, a));
objnewArray.forEach(a => Object.keys(a).forEach(k => hash.get(a.id)[k] = a[k]));

console.log(objnewArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6 with Array#find

var objArray = [{ Id: 1, Val: 'A' }, { Id: 3, Val: 'B' }, { Id: 5, Val: 'C' }],
    objnewArray = [{ Id: 1, Value: 'AA', extra: 42 }, { Id: 3, Value: 'BB' }, { Id: 5, Value: 'CC' }];

objnewArray.forEach(a =>
    Object.keys(a).forEach(k => objArray.find(b => a.id === b.id)[k] = a[k]));

console.log(objnewArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments