簡體   English   中英

如何在javascript(lodash)中替換對象數組中的對象

[英]How to replace an object in object array in 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”相同的對象替換數組中的對象。 因此得到的數組將是:

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

另外,如果具有該id的對象不存在,我需要將該對象添加到數組中。

如何使用最少的lodash代碼實現這一目標 尋找類似的東西

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

你可以用_.unionBy

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

但請在此評論中查看備注

你可以使用.findIndex()

var i = arr.findIndex(o => o.id === obj.id);
if (arr[i]) { arr[i] = obj } else { arr.push(obj) };

您可以將_.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> 

這是一個使用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> 

你可以循環並使用'拼接'功能:

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);

編輯:錯過了附加條件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM