js对比两个数组对象里的某个属性相等,并改变里面的字段值

两个数组对象

const list1 = [
  {type: 0, val: 2},
  {type: 1, val: 3},
  {type: 2, val: 5},
  {type: 3, val: 10},
  {type: 4, val: 9},
  {type: 5, val: 7},
]
const list2 = [
  {type:2, count: 10},
  {type:4, count: 14},
]

要判断:list1里面的type,与list2的type相同的话,就改变list1对象里的val值为list2对象里的count,如果不同的话,就设为0

预期的结果

list1 = [
  {type: 0, val: 0},
  {type: 1, val: 0},
  {type: 2, val: 10},
  {type: 3, val: 0},
  {type: 4, val: 14},
  {type: 5, val: 0},
]

现在的实现代码

const searType = list2.map(i => i.type);
const searNum = list2.map(n => n.count);
list1.forEach(l => {
  if (l.type == searType) l.val = searNum[0];
  else l.val = 0;
});

怎么能精简点

阅读 8.6k
3 个回答
const map = Object.fromEntries(list2.map(({ type, count }) => [type, count]));
const result = list1.map(({ type }) => ({ type, val: map[type] ?? 0 }));
console.log(result);

如果要直接改变 list1,就用 forEach 代替 map

list1.forEach(it => it.val = map[it.type] ?? 0);
console.log(list1);

不建映射表,直接查也可以。下面是 map 写法改的,可以自己改成 forEach 写法

const r = list1.map(({ type }) => {
    return {
        type,
        val: list2.find(it => it.type === type)?.count ?? 0
    };
});
        list1.forEach((item) => {
            let i = list2.find((i) => i.type === item.type);
            item.val = i?.count || 0;
        });
        console.log(list1);
function transform(a, b) {
    loop: for (var i = 0; i < a.length; ++i) {
        for (var j = 0; j < b.length; ++j) {
            if (a[i].type === b[j].type) {
                a[i].val = b[j].count;
                continue loop;
            }
        }
        a[i].val = 0;
    }
    return a;
}
console.dir(transform(list1, list2));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏