如果存在则更新或将新元素添加到对象数组 - javascript + lodash 中的优雅方式 [英] Update if exists or add new element to array of objects - elegant way in javascript + lodash

查看:74
本文介绍了如果存在则更新或将新元素添加到对象数组 - javascript + lodash 中的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个这样的对象数组:

So I have an array of objects like that:

var arr = [
  {uid: 1, name: "bla", description: "cucu"},
  {uid: 2, name: "smth else", description: "cucarecu"},
]

uid 是该数组中对象的唯一 id.我正在寻找一种优雅的方式来修改对象,如果我们有给定 uid, 的对象或添加一个新元素,如果呈现的 uid 不存在在数组中.我想象这个函数在 js 控制台中的行为是这样的:

uid is unique id of the object in this array. I'm searching for the elegant way to modify the object if we have the object with the given uid, or add a new element, if the presented uid doesn't exist in the array. I imagine the function to be behave like that in js console:

> addOrReplace(arr, {uid: 1, name: 'changed name', description: "changed description"})
> arr
[
  {uid: 1, name: "bla", description: "cucu"},
  {uid: 2, name: "smth else", description: "cucarecu"},
]
> addOrReplace(arr, {uid: 3, name: 'new element name name', description: "cocoroco"})
> arr
[
  {uid: 1, name: "bla", description: "cucu"},
  {uid: 2, name: "smth else", description: "cucarecu"},
  {uid: 3, name: 'new element name name', description: "cocoroco"}
]

我目前的方式似乎不太优雅和实用:

My current way doesn't seem to be very elegant and functional:

function addOrReplace (arr, object) {
  var index = _.findIndex(arr, {'uid' : object.uid});
  if (-1 === index) {
    arr.push(object);
  } else {
    arr[index] = object;
  }
} 

我正在使用 lodash,所以我在考虑修改 _.union 和自定义相等性检查之类的东西.

I'm using lodash, so I was thinking of something like modified _.union with custom equality check.

推荐答案

您可以使用对象代替数组:

var hash = {
  '1': {uid: 1, name: "bla", description: "cucu"},
  '2': {uid: 2, name: "smth else", description: "cucarecu"}
};

键是 uids.现在你的函数 addOrReplace 很简单:

The keys are the uids. Now your function addOrReplace is simple like this:

function addOrReplace(hash, object) {
    hash[object.uid] = object;
}

<小时>

更新

除了数组之外,还可以将对象用作索引.
通过这种方式,您可以快速查找以及一个有效的数组:

It's also possible to use an object as an index in addition to the array.
This way you've got fast lookups and also a working array:

var arr = [],
    arrIndex = {};

addOrReplace({uid: 1, name: "bla", description: "cucu"});
addOrReplace({uid: 2, name: "smth else", description: "cucarecu"});
addOrReplace({uid: 1, name: "bli", description: "cici"});

function addOrReplace(object) {
    var index = arrIndex[object.uid];
    if(index === undefined) {
        index = arr.length;
        arrIndex[object.uid] = index;
    }
    arr[index] = object;
}

看看jsfiddle-demo(一个面向对象的解决方案你会找到这里)

这篇关于如果存在则更新或将新元素添加到对象数组 - javascript + lodash 中的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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