Good evening! Struggling with searches for a long time, help to understand? Suppose there are arrays # 1 and # 2, now I’ll present them below:


var array1 = [ {elem_id: 1, name: 'Watch', active: true}, {elem_id: 2, name: 'System', active: false}, {elem_id: 3, name: 'Process', active: false, ... ]; var array2 = [ {category: 'App', name: 'Watch', active: false}, {category: 'App', name: 'Table', active: true}, {category: 'App', name: 'System', active: false}, {category: 'App', name: 'Process', active: true}, ... ]; 

It is necessary to achieve such that on an output the array with the joint data turned out. The check must be by 'name'. If it is the same, then the value is 'active', should migrate from the array # 1 and the array # 2. Now I shall depict what should come out as a result of my examples.


Because in the first array and in the second are the same 'name' - this is "Watch, System, Process", then all the data of the second array fall into the array # 3, but with the 'active' parameters from the first array. Total:

 var array3 = [ {category: 'App', name: 'Watch', active: true}, // было false, стало true; {category: 'App', name: 'Table', active: true}, {category: 'App', name: 'System', active: false}, {category: 'App', name: 'Process', active: false}, // было true, стало false; ... ]; 

Thank you very much!

  • Use keys instead of iteration - if 'Watch', 'System', .. become keys of arrays (that is, it will not be an array anymore but an object for JS). That algorithm will be much easier. - Goncharov Alexander

1 answer 1

 var array1 = [{ elem_id: 1 ,name: 'Watch', active: true }, { elem_id: 2, name: 'System', active: false }, { elem_id: 3, name: 'Process', active: false }]; var array2 = [{ category: 'App', name: 'Watch', active: false }, { category: 'App', name: 'Table', active: true }, { category: 'App', name: 'System', active: false }, { category: 'App', name: 'Process', active: true }]; var array3 = []; for (var obj of array2) { /* ищем элемент первого массива с соответсвующим именем */ var obj1 = array1.find((el) => { if (el.name == obj.name) return el; }); var active; /* вычисляем active */ if (obj1) { active = obj1.active; } else { active = obj.active; } /* создаём объект для нового результирующего массива array3 на основе obj из array2 */ var newObj = Object.assign({},obj); /* задаём active */ newObj.active = active; /* добавляем в array3 */ array3.push(newObj); } console.log(array3); 

  • Thank you very much, work + figured out! - LiveD