简体   繁体   English

用JavaScript合并两个对象数组

[英]merge two array of objects with javascript

I have this 2 array of objects like this: 我有2个这样的对象数组:

objects [ { countMedias: 2 },
  { countMedias: 1 },
  { countMedias: 3 },
  { countMedias: 1 },
  { countMedias: 2 } ]
listePlayliste [ { nom_playlist: 'bbbb' },
  { nom_playlist: 'ccc' },
  { nom_playlist: 'aaaa' },
  { nom_playlist: 'xxxx' },
  { nom_playlist: 'resttttttttt' } ]

I want to fusion both of them to get something like this : 我想融合他们两个,以获得这样的东西:

Result [ { nom_playlist: 'bbbb', countMedias: 2 },
  { nom_playlist: 'ccc', countMedias: 1  },
  { nom_playlist: 'aaaa', countMedias: 3 },
  { nom_playlist: 'xxxx', countMedias: 1 },
  { nom_playlist: 'resttttttttt', countMedias: 2 } ]

I tried this but it is not what I want actually: 我尝试了这个,但实际上不是我想要的:

    Array.prototype.push.apply(json,objects); 

Maybe something like this: 也许是这样的:

objects.map((object, index) => Object.assign(object, listePlayliste[index]))

Don't try to use this on a large array size though. 但是不要尝试在较大的数组大小上使用它。 It's not that fast. 没那么快。

use map . 使用map Iterate over one of the array and return the object, which holds the current obj and object from other array using index. 遍历数组之一并返回对象,该对象使用索引保存其他数组中的当前obj和对象。

 const objects = [{ countMedias: 2 }, { countMedias: 1 }, { countMedias: 3 }, { countMedias: 1 }, { countMedias: 2 } ]; const listePlayliste = [{ nom_playlist: 'bbbb' }, { nom_playlist: 'ccc' }, { nom_playlist: 'aaaa' }, { nom_playlist: 'xxxx' }, { nom_playlist: 'resttttttttt' } ]; const output = objects.map((obj, i) => ({ ...obj, ...listePlayliste[i] })); console.log(output); 

Similar to objects.map(), a for loop will also work, but please be noted that, Object.assign() will modify the original array. 与objects.map()类似,for循环也可以使用,但请注意, Object.assign()将修改原始数组。 PFB code snippet: PFB代码段:

 objects = [ { countMedias: 2 }, { countMedias: 1 }, { countMedias: 3 }, { countMedias: 1 }, { countMedias: 2 } ]; listePlayliste = [ { nom_playlist: 'bbbb' }, { nom_playlist: 'ccc' }, { nom_playlist: 'aaaa' }, { nom_playlist: 'xxxx' }, { nom_playlist: 'resttttttttt' } ]; for (let i=0; i<objects.length; i++) { Object.assign(objects[i], listePlayliste[i]); } console.log(objects); 

To avoid modifying original array, we can use Spread syntax . 为了避免修改原始数组,我们可以使用Spread语法 PFB code snippet: PFB代码段:

 objects = [ { countMedias: 2 }, { countMedias: 1 }, { countMedias: 3 }, { countMedias: 1 }, { countMedias: 2 } ]; listePlayliste = [ { nom_playlist: 'bbbb' }, { nom_playlist: 'ccc' }, { nom_playlist: 'aaaa' }, { nom_playlist: 'xxxx' }, { nom_playlist: 'resttttttttt' } ]; var result = []; for (let i=0; i<objects.length; i++) { result.push({ ...objects[i], ...listePlayliste[i] }) } console.log(result); console.log(objects); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM