javascript - 用另一个对象数组过滤对象数组,并为匹配的对象添加额外的键
问题描述
我有以下两个数组,我想获得第二个数组,但匹配的对象应该包含一个额外的键“select”:true,而不匹配的对象应该包含“select”:false。
var firstArray = [{id: -1, type: "group"},
{id: -2, type: "group"}];
var secondArray = [{id: -3, type: "group"},
{id: -2, type: "group"},
{id: -1, type: "group"}];
预期结果:
var expectedArray = [{id: -1, type: "group", select: true},
{id: -2, type: "group", select: true},
{id: -3, type: "group", select: false}];
我试过下面的代码:
for(var i=0;i<firstArray.length;i++){
for(var j=0;j<secondArray.length;j++){
console.log(firstArray[i].id,secondArray[j].id)
if(firstArray[i].id===secondArray[j].id){
if(secondArray[j].hasOwnProperty('select')){
secondArray[j].select=true;
// console.log('true select property',secondArray[j].select)
}
else{
secondArray[j].select=true;
// console.log('true adding new',secondArray[j].select)
}
}else{
secondArray[j]['select']=false;
// console.log('false not match',secondArray[j].select)
}
}
}
解决方案
您可以创建Set
所有 id 中存在的firstArray
. 然后根据是否设置id循环secondArray
使用forEach
和添加值select
has
let firstArray=[{id:-1,type:"group"},{id:-2,type:"group"}],
secondArray=[{id:-3,type:"group"},{id:-2,type:"group"},{id:-1,type:"group"}];
const ids = new Set(firstArray.map(a => a.id));
secondArray.forEach(a => a.select = ids.has(a.id))
console.log(secondArray)
推荐阅读
- haskell - ghci:模块导入没有错误,但没有找到
- ruby-on-rails - 无法在 Vue.js 中显示我的 ActiveStorage 文件(Ruby on Rails Active Storage)
- python - 在嵌套列表中搜索
- javascript - 如何让 require.context 与带有/不带有 Craco 的 Create React App 一起工作?
- php - 无法通过 docker-compose 上的 php pdo 连接到 postgresql
- angular - 根据 ionic 中的创建日期对用户列表进行排序
- reactjs - 如何在连接的 redux 选择器中使用反应路由参数?
- string - C#重命名字符串?|| 给字符串一个字符串的名称?
- flask - 从 Quart 中的另一个任务访问 app_context
- github-actions - 如何在 GitHub Actions 表达式语法中引用上下文值?