[英]In JavaScirpt, how do I filter the elements of the same field in two arrays and return a new two-dimensional array
This is an example:这是一个例子:
I want to regroup arry2 according to the fields in arry1我想根据 arry1 中的字段重新组合 arry2
var arry1 = [
{id: 1, parentId: 0, name: "phone"},
{id: 2, parentId: 1, name: "nick"}
];
var arry2 = [
{id: 7, parentId: 0, name: "phone_item1"},
{id: 8, parentId: 1, name: "phone_item2"},
{id: 9, parentId: 0, name: "nick_item1"},
{id: 10, parentId: 1, name: "nick_item2"}
];
let newArrys = arry1.filter((item)=>{
return leve_two.indexOf(arry2.parentId) == -1
})
I want to return a two-dimensional array:我想返回一个二维数组:
[[
{id: 7, parentId: 0, name: "phone_item1"},
{id: 9, parentId: 0, name: "nick_item1"}
],[
{id: 8, parentId: 1, name: "phone_item2"},
{id: 10, parentId: 1, name: "nick_item2"}
]]
I tried Array.filter
and so on.我试过
Array.filter
等等。
Can you help me?你能帮助我吗?
You can use filter()
method along-with Object.values()
to get the desired output:您可以使用
filter()
方法和Object.values()
来获得所需的输出:
const arr1 = [ {id: 1, parentId: 0, name: "phone", level: 0, productCount: 0}, {id: 2, parentId: 1, name: "nick", level: 0, productCount: 0} ]; const arr2 = [ {id: 7, parentId: 0, name: "phone_item1", level: 1, productCount: 0}, {id: 8, parentId: 1, name: "phone_item2", level: 1, productCount: 0}, {id: 9, parentId: 0, name: "nick_item1", level: 1, productCount: 0}, {id: 10, parentId: 1, name: "nick_item2", level: 1, productCount: 0} ]; const filterIds = arr1.map(({ parentId }) => parentId); const arr3 = Object.values(arr2.reduce((r, c) => { r[c.parentId] = r[c.parentId] || []; r[c.parentId].push(c); return r; }, {})); console.log(arr3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
It looks just like grouping arry2
by parentId
and arry1
looks useless 🤔看起来就像按
parentId
将arry2
分组而arry1
看起来没用🤔
Use some lib for this.为此使用一些库。 For example Ramda way:
例如 Ramda 方式:
const result = R.pipe(
R.groupBy(R.prop("parentId")),
R.toPairs,
R.map(R.last)
)(arry2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.