简体   繁体   English

在javascript中比较和合并数组

[英]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}]

i have 2 arrays like above.我有 2 个像上面这样的数组。 i want to result should be我想结果应该是

arr1 = [{id:1, checked:true},{id:2, checked:false},{id:3, checked:true}]

i tried with array filter, but it gives joined array我尝试使用数组过滤器,但它提供了连接数组

companyArr.forEach(citem => {
        mapItem.forEach(mitem => {
            companyArr.push({
            Id: citem.Id,
            CompanyName: citem.CompanyName,
            isChecked: (mitem.company_id === citem.Id)
          })
        })
      })

You could make a Set which keeps all your ids from each object in arr2 , and then use .map() on arr1 to check the checked values based on whether the set has the current objects 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 */

Note: I've created a set here for efficient lookup, however, you could use .some() on arr2 if you wish in the .map() as well, but this would have performance drawbacks for large data sets:注意:我在此处创建了一个集合以进行高效查找,但是,如果您希望在.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 */

you could use Array#map for recreate the array .And Array#findIndex for find the first array value exist on 2nd array .And use Spread operator for easy to split the object您可以使用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)

You can use map and find for that.您可以使用mapfind它。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM