javascript - jquery update property in an array from another array -


i want update property in array array matching field using jquery.

objarray = [ { id: 1, val: 'a'}, { id: 3, val: 'b'}, { id: 5, val: 'c'} ]; 

after doing processing, getting array this.

objnewarray = [ { id: 1, value: 'aa'}, { id: 3, value: 'bb'}, { id: 5, value: 'cc'} ]; 

now want update objarray val field objnewarray's value field result

 objarray = [ { id: 1, val: 'aa'}, { id: 3, val: 'bb'}, { id: 5, val: 'cc'} ]; 

is there other way other looping both arrays ,matching id , updating val property?

you use hash table , loop target first , the new object assigning 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 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 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

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -