如何在JavaScript中替换对象数组中的对象(Lodash) [英] How to replace an object in object array in javascript (lodash)

查看:2263
本文介绍了如何在JavaScript中替换对象数组中的对象(Lodash)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象数组:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "abc",
    status: false
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: true
  },
  ...
]

我有这个对象:

var obj = {
  id      : "a1",
  guid    : "sdfsfd",
  ...
  value   : "xyz",
  status  :  true
}

我需要用"id"相同的该对象替换数组中的对象.因此,结果数组将为:

I need to replace the object in the array with this object where the "id" is same. So the resulting array will be:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "xyz",
    status: true
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: true
  },
  ...
]

此外,如果不存在具有该ID的对象,则需要将该对象添加到数组中.

Additionally I need to add this object to the array if an object with that id doesn't exists.

如何使用最少的 lodash 代码来实现这一目标? 寻找类似

How to achieve this using minimal lodash code? Looking for something like

arr = _.merge_by_key(arr,obj,"id");

推荐答案

您可以使用_.unionBy

var res = _.unionBy([obj], arr, 'id');

,但请查看 查看全文

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