[英]How to replace an object in object array in javascript (lodash)
I have following object array: 我有以下对象数组:
var arr = [
{
id : "a1",
guid : "sdfsfd",
...
value : "abc",
status: false
},
{
id : "a2",
guid : "sdfsfd",
...
value : "def",
status: true
},
...
]
I have this object: 我有这个对象:
var obj = {
id : "a1",
guid : "sdfsfd",
...
value : "xyz",
status : true
}
I need to replace the object in the array with this object where the "id" is same. 我需要用“id”相同的对象替换数组中的对象。 So the resulting array will be:
因此得到的数组将是:
var arr = [
{
id : "a1",
guid : "sdfsfd",
...
value : "xyz",
status: true
},
{
id : "a2",
guid : "sdfsfd",
...
value : "def",
status: true
},
...
]
Additionally I need to add this object to the array if an object with that id doesn't exists. 另外,如果具有该id的对象不存在,我需要将该对象添加到数组中。
How to achieve this using minimal lodash code? 如何使用最少的lodash代码实现这一目标 ? Looking for something like
寻找类似的东西
arr = _.merge_by_key(arr,obj,"id");
you can do it with _.unionBy
你可以用
_.unionBy
var res = _.unionBy([obj], arr, 'id');
but check a note at this comment 但请在此评论中查看备注
You can use .findIndex()
你可以使用
.findIndex()
var i = arr.findIndex(o => o.id === obj.id);
if (arr[i]) { arr[i] = obj } else { arr.push(obj) };
You can use _.findIndex
with the _.matchesProperty
shorthand: 您可以将
_.findIndex
与_.matchesProperty
简写一起使用:
var index = _.findIndex(arr, ['id', obj.id]);
arr[index >= 0 ? index : arr.length] = obj;
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 }; var index = _.findIndex(arr, ['id', obj.id]); arr[index >= 0 ? index : arr.length] = obj; console.log(arr);
.as-console-wrapper { min-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Here's a lodash solution that uses keyBy to create an object wherein each item in the collection is represented by their id
, set to override the new object or possibly add the new object and lastly values to get the array representation of the object. 这是一个使用keyBy创建对象的lodash解决方案,其中集合中的每个项目由其
id
表示, 设置为覆盖新对象或可能添加新对象,最后是值以获取对象的数组表示。
var result = _(arr).keyBy('id').set(obj.id, obj).values().value();
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 } var result = _(arr).keyBy('id').set(obj.id, obj).values().value(); console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
you can loop and use 'splice' function: 你可以循环并使用'拼接'功能:
var added = false;
for(var i=0;i<arr.length; i++){
if(arr[i].id === obj.id){
arr.splice(i,1,obj);
added = true;
break;
}
}
if(!added) arr.push(obj);
EDIT: missed added condition 编辑:错过了附加条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.