[英]How to filter this array of object in Node.js?
I have some data which looks like this-我有一些看起来像这样的数据-
[
{
"element": 1,
"id": 1
},
{
"element": 1,
"id": 2
},
{
"element": 2,
"id": 1
},
{
"element": 2,
"id": 2
},
{
"element": 3,
"id": 1
}
]
I have data as above as it is array of object and I want to filter as given below mainly in Node.js where I want to filter with element and return new array.我有上面的数据,因为它是 object 的数组,我想过滤如下,主要在 Node.js 中,我想用元素过滤并返回新数组。 It will be helpful if I get any solution for this.
如果我对此有任何解决方案,将会很有帮助。
[
{
"element": 1,
"data": [
{
"element": 1,
"id": 1
},
{
"element": 1,
"id": 2
}
]
},
{
"element": 2,
"data": [
{
"element": 2,
"id": 1
}
]
},
{
"element": 3,
"data": [
{
"element": 3,
"id": 1
}
]
}
]
Okay, so let's get some variables in:好的,让我们在其中获取一些变量:
const elementsData = [{ element: 0001, id: 1 }, { element: 0001, id: 2 }, { element: 0001, id: 3 }, { element: 0001, id: 4 }, { element: 0002, id: 1 }, { element: 0002, id: 2 }, { element: 0002, id: 3 }, { element: 0003, id: 1 } ]
First, You'll need to filter out the unique element values:首先,您需要过滤掉唯一的元素值:
const uniqueElements = []
elementsData.forEach(datum => {
if (!uniqueElements.includes(datum.element)) {
uniqueElements.push(datum.element)
}
})
Then do groupings by uniqueElement然后按 uniqueElement 进行分组
// loop through the unique Elements
const output = uniqueElements.map(uniqueElement => {
// this will return the object with the specified fields
return {
// element value
element: uniqueElement,
// filter through elementsData for matching elements and save then into an array.
// You can do sort() here if you want to sort them by id, but this is basically it
data: elementsData.filter(elementData => elementsData.element === uniqueElement)
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.