更新是否存在或添加新元素对象数组 - 在JavaScript优雅的方式+ lodash [英] Update if exists or add new element to array of objects - elegant way in 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对象,
或添加新的元素,如presented 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,所以我想的有点像修改 _。工会
自定义平等检查。
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"}
};
的键是的uid 。现在,你的函数 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-演示 (一种面向对象的解决方案你会发现这里)
这篇关于更新是否存在或添加新元素对象数组 - 在JavaScript优雅的方式+ lodash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!