两个数组的操作

arr1 = [
{active:true, id:1,name: '业务类型'},
{active:true, id:2,name: '报表类型'},
{active:true, id:3,name: '资产类型'},
]

arr2 = [
{active:false, id:1,name: '业务类型'},
{active:false, id:2,name: '报表类型'},
{active:false, id:3,name: '资产类型'},
{active:false, id:4,name: '商业类型'},
{active:false, id:5,name: '报销类型'}
]

最终要的是arr2 = [
{active:true, id:1,name: '业务类型'},
{active:true, id:2,name: '报表类型'},
{active:true, id:3,name: '资产类型'},
{active:false, id:4,name: '商业类型'},
{active:false, id:4,name: '报销类型'}
]
目的只要把arr2的有包含arr1想的active改成true,没有包含arr1项的active就不修改,没有思路 试了用几种方法,都没成功

阅读 2.5k
4 个回答
没有思路 试了用几种方法,都没成功

请把你用过的几种方法贴出来,让大家知道你曾经努力过

以下是我的思路

const arr1 = [
    {active:true, id:1,name: "业务类型"},
    {active:true, id:2,name: "报表类型"},
    {active:true, id:3,name: "资产类型"},
];
const arr2 = [
    {active:false, id:1,name: "业务类型"},
    {active:false, id:2,name: "报表类型"},
    {active:false, id:3,name: "资产类型"},
    {active:false, id:4,name: "商业类型"},
    {active:false, id:5,name: "报销类型"}
];
const set = new Set();
arr1.forEach(item=>set.add(item.id));
arr2.forEach(item=>{
    if(set.has(item.id)){
        item.active = true;
    }
});

console.table(arr2);

以下是运行结果

clipboard.png

// 创建映射
const map = arr1.reduce((p, c) => [p[c.name] = p[c.name] || true, p][1], {})
// 获取映射结果
const result = arr2.map(item => [map[item.name] && (item.active = true), item][1]])

话说这两行代码我已经用来回答三四个类似的问题了,都是这两天的,中午还回答了一个,你这个问题好像之前就有个几乎一样的啊...

arr1 = [
{active:true, id:1,name:'业务类型'},
{active:true, id:2,name:'报表类型'},
{active:true, id:3,name:'资产类型'}
]

arr2 = [
{active:false, id:1,name: '业务类型'},
{active:false, id:2,name: '报表类型'},
{active:false, id:3,name: '资产类型'},
{active:false, id:4,name: '商业类型'},
{active:false, id:5,name: '报销类型'}
]

let obj = {};
arr1.forEach(item=>{
    obj[item.id] = item;
});

arr2.forEach(item=>{
    if(obj[item.id]){
        item.active = true;
    }
})
const arr1 = [
    {active:true, id:1,name: "业务类型"},
    {active:true, id:2,name: "报表类型"},
    {active:true, id:3,name: "资产类型"},
];
const arr2 = [
    {active:false, id:1,name: "业务类型"},
    {active:false, id:2,name: "报表类型"},
    {active:false, id:3,name: "资产类型"},
    {active:false, id:4,name: "商业类型"},
    {active:false, id:5,name: "报销类型"}
];
arr2.map(v2 => {
    const member = arr1.find(v1 => v1.id === v2.id);
    return member && member.active ? {...v2, active: member.active} : v2
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题