[英]Check if ID Is Found Another Array in ES6
I wanted to filter out the data.我想过滤掉数据。 I wanted to check if data on
data1
is found on data2
and to check if it has errorMessages.我想检查是否在
data2
上找到了data1
上的数据,并检查它是否有 errorMessages。 Please check my code below.请在下面检查我的代码。 Is there a better way to do it?
有更好的方法吗?
data1数据1
[
{
"ids": "0111",
},
{
"ids": "0222",
},
{
"ids": "0333",
}
]
data2数据2
[
{
"id": "0111",
"errorMessages": [
{
"message": ["sample error message 1"]
}
]
},
{
"id": "0333",
"errorMessages": []
}
]
Code代码
const output= data1.filter(
(element) => element.ids === data2.find((data) => data).id
);
console.log("output", output);
.find((data) => data)
doesn't do anything useful - each item in the array is an object, which is truthy, so that'll always return the first element in the array. .find((data) => data)
没有做任何有用的事情——数组中的每个项目都是一个 object,这是真的,所以它总是返回数组中的第一个元素。
If you did want to .find
a matching element in the other array - then a better approach would be to make a Set of the IDs found in the other array first (Set lookup is much quicker - O(1)
- than .find
, which is O(n)
).如果您确实想
.find
另一个数组中的匹配元素 - 那么更好的方法是首先制作在另一个数组中找到的一组 ID(Set 查找比.find
快得多 - O(1)
,这是O(n)
)。
You also need to implement the logic to check if the errorMessages
is empty.您还需要实现逻辑来检查
errorMessages
是否为空。
const data1 = [ { "ids": "0111", }, { "ids": "0222", }, { "ids": "0333", } ] const data2 = [ { "id": "0111", "errorMessages": [ { "message": ["sample error message 1"] } ] }, { "id": "0333", "errorMessages": [] } ] const ids = new Set( data2.filter(item => item?.errorMessages.length).map(item => item.id) ); const output= data1.filter( element => ids.has(element.ids) ); console.log("output", output);
Without Set, but use Object as the map.没有设置,但使用 Object 作为 map。
const IDKeys = {};
data2.forEach(data => {
if (data.errorMessages.length){
IDKeys[data.id] = true; // means valid
}
})
const filteredArray = data1.filter(data => IDKeys[data.id]);
This would be only O(n) since accessing key on object is O(1)这将只是 O(n),因为访问 object 上的密钥是 O(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.