如何解决如何通过另一个对象数组过滤对象数组并将键/值添加到结果数组?
我说两个数组
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。