[英]compare and merge array in javascript
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}]
const arr2 = [{id:1},{id:3}]
我有 2 个像上面这样的数组。 我想结果应该是
arr1 = [{id:1, checked:true},{id:2, checked:false},{id:3, checked:true}]
我尝试使用数组过滤器,但它提供了连接数组
companyArr.forEach(citem => {
mapItem.forEach(mitem => {
companyArr.push({
Id: citem.Id,
CompanyName: citem.CompanyName,
isChecked: (mitem.company_id === citem.Id)
})
})
})
您可以创建一个Set来保存arr2
每个对象的所有 id,然后在arr1
上使用.map()
根据该集合是否具有当前对象 id checked
值:
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}] const arr2 = [{id:1},{id:3}]; const lut = new Set(arr2.map(({id}) => id)); const res = arr1.map(o => ({...o, checked: lut.has(o.id)})) console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore */
注意:我在此处创建了一个集合以进行高效查找,但是,如果您希望在.map()
中也可以在 arr2 上使用.some()
,但这会对大型数据集产生性能缺陷:
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}] const arr2 = [{id:1},{id:3}]; const res = arr1.map(o => ({...o, checked: arr2.some(({id}) => id === o.id)})); console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore */
您可以使用Array#map
重新创建数组。和Array#findIndex
用于查找第二个数组中存在的第一个数组值。并使用Spread 运算符来轻松拆分对象
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}] const arr2 = [{id:1},{id:3}] let res = arr1.map(a=> ({...a,checked: arr2.findIndex(({id}) => id == a.id) > -1})); console.log(res)
您可以使用map
并find
它。
const arr1 = [{ id: 1, checked: false }, { id: 2, checked: false }, { id: 3, checked: false }] , arr2 = [{ id: 1 }, { id: 3 }] , result = arr1.map(el => ({ ...el, checked: !!arr2.find(({ id }) => id === el.id) })); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.