如何通过另一个对象数组过滤对象数组并将键/值添加到结果数组?

问题描述

我说两个数组

const array1 = [{ID: 1,msg: "xxx"},{ID: 2,msg: "eeee"},{ID: 3,msg: "ffff"},{ID: 4,msg: "yyy"}]
const array2 = [{intensity: 1,location: "AAAAA"},{intensity: 1,location: "WWWWW"},{intensity: 4,location: "RRRRR"}]

您会注意到,intensity中的array2不是唯一的。

我设法在array1的{​​{1}}中找到对象,但是用以下一行找到了单个对象(不过滤重复项):

ID === intensity

这里的const resultArray = array1.filter((elem) => array2.find(({ intensity }) => elem.ID === intensity));

resultArray

但是所需的输出应该是

resultArray = [{ID: 1,msg: "yyy"}]

我想在有匹配项的地方将resultArray = [{ID: 1,msg: "yyy"}] 添加location,所以resultArray应该是

resultArray

解决方法

您可以为消息创建一个哈希表并映射所需的属性。

__
const
    array1 = [{ ID: 1,msg: "xxx" },{ ID: 2,msg: "eeee" },{ ID: 3,msg: "ffff" },{ ID: 4,msg: "yyy" }],array2 = [{ intensity: 1,location: "AAAAA" },{ intensity: 1,location: "WWWWW" },{ intensity: 4,location: "RRRRR" }],msgs = array1.reduce((m,o) => (m[o.ID] = o,m),{}),result = array2.map(({ intensity,location }) =>
        ({ ...msgs[intensity],location }));

console.log(result);

,

我的方式。

const array1 = 
      [ { ID: 1,msg: "xxx"},msg: "eeee"},msg: "ffff"},msg: "yyy"} 
      ] 
       
const array2 = 
      [ { intensity: 1,location: "AAAAA"},location: "WWWWW"},location: "RRRRR"} 
      ] 
 
const resultArray = array1.reduce((t,a1)=>
      {
      array2
        .filter(x=>a1.ID===x.intensity)
        .forEach (({ intensity,...others})=>
          { t.push( {...a1,...others} ) } )
      return t
      },[])

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

,

为array1元素构建一个对象,以便在进行array2映射时更快地进行访问。

const array1 = [
  { ID: 1,msg: "yyy" },];
const array2 = [
  { intensity: 1,location: "RRRRR" },];

const all = {};
array1.forEach(({ ID,msg }) => (all[ID] = msg));

const res = array2.map(({ intensity,location }) => ({
  ID: intensity,msg: all[intensity],location,}));

console.log(res)

或者,如果您对array1的数据大小不是很在意,可以在array1上使用find直接获取msg

const array1 = [
  { ID: 1,];

const res = array2.map(({ intensity,msg: array1.find(({ ID }) => ID === intensity)?.msg ?? '',}));

console.log(res)