我有这个对象数组:
const data = [
{
id: 1,
name: 'Name1',
encryptionKey: 'AAA'
},
{
id: 2,
name: 'Name2',
encryptionKey: 'BBB'
},
{
id: 3,
name: 'Name3',
encryptionKey: 'CCC'
}
]
以及另一个加密 key 数组:
const encryptionKeys = ['AAA', 'BBB']
然后,我根据 encryptionKeys
数组过滤 data
数组,如下所示:
var filtered = data.filter(function(item) {
return encryptionKeys.indexOf(item.encryptionKey) !== -1;
});
它有效并过滤对象并将它们保存在新数组中。然而,问题是如果 encryptionKey
数组具有重复的 key ,例如:
const encryptionKeys = ['AAA', 'BBB', 'BBB']
那么所有重复的键都将被忽略,在这种情况下,过滤后的数组将只有 2 个对象,而不是 3 个。我在过滤代码中做错了什么?如果 encryptionKeys
数组具有重复的值,则过滤后的数组应具有重复的对象。
最佳答案
记下.flat()的浏览器兼容性,然后查看@babel/polyfill
const data = [
{
id: 1,
name: 'Name1',
encryptionKey: 'AAA'
},
{
id: 2,
name: 'Name2',
encryptionKey: 'BBB'
},
{
id: 3,
name: 'Name3',
encryptionKey: 'CCC'
}
]
const keys = ['AAA', 'BBB', 'BBB', 'AAA', 'BBB', 'ZZZ']
const occurances = data.map(d => {
const { encryptionKey } = d
const keyedOccurances = keys
.filter(k => k === encryptionKey)
.map(k => encryptionKey === k && d)
return keyedOccurances.length && keyedOccurances
})
.filter(Boolean)
.flat()
console.log(occurances)
关于javascript - 通过具有重复键的另一个数组过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55414305/