使用属性上的另一个对象数组替换对象数组 [英] replace array of object with another array of object base on property

查看:160
本文介绍了使用属性上的另一个对象数组替换对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用另一个对象数组来替换对象数组?

How to replace array of object with another array of object base on property?

var arr = [
    {'status':'ok'},
    {'status':'ok'},
    {'status':'error'}
]

var arr2 = [
    {'status':error, 'msg': 'etc', 'more property':true}
]

arr = arr.forEach((obj,i) => { if(obj.status === 'error'){obj = arr2[i]} return obj })

我的上述代码失败,状态ok已经不见了,我想知道有什么问题。

My above code failed, status ok is gone, I wonder what is wrong.

推荐答案

p>您可以使用 Array#map()来创建一个新数组,并将 Array#find()找到第二个数组中的对象

You can do it using Array#map() to create a new array and Array#find() to find the object in the second array

let arr=[{status:"ok"},{status:"ok"},{status:"error"}],
arr2=[{status:"error",msg:"etc","more property":!0}];

arr = arr.map(a=>{
  let fullObj = arr2.find(a2=>a2.status===a.status);
  return fullObj ? fullObj : a;
});

console.log(arr);

这篇关于使用属性上的另一个对象数组替换对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆