簡體   English   中英

JavaScript 通過 id 合並對象

[英]JavaScript merging objects by id

在 Javascript 中合並兩個數組的正確方法是什么?

我有兩個數組(例如):

var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]

我希望能夠得到類似的結果:

var a3 = [{ id : 1, name : "test", count : "1"}, 
          { id : 2, name : "test2", count : "2"}]

根據“id”字段連接兩個數組的位置,並且只是添加了額外的數據。

我嘗試使用_.union來執行此操作,但它只是將第二個數組中的值覆蓋到第一個數組中

這應該可以解決問題:

var mergedList = _.map(a1, function(item){
    return _.extend(item, _.findWhere(a2, { id: item.id }));
});

這假設 a1 中第二個對象的 id 應該是 2 而不是“2”

簡短的 ES6 解決方案

const a3 = a1.map(t1 => ({...t1, ...a2.find(t2 => t2.id === t1.id)}))

假設 ID 是字符串並且順序無關緊要,您可以

  1. 創建哈希表。
  2. 迭代這兩個數組並將數據存儲在由 ID 索引的哈希表中。 如果已經有一些具有該 ID 的數據,請使用Object.assign更新它(ES6,可以是polyfill )。
  3. 獲取一個包含哈希映射值的數組。
var hash = Object.create(null);
a1.concat(a2).forEach(function(obj) {
    hash[obj.id] = Object.assign(hash[obj.id] || {}, obj);
});
var a3 = Object.keys(hash).map(function(key) {
    return hash[key];
});

在 ECMAScript6 中,如果 ID 不一定是字符串,則可以使用Map

var hash = new Map();
a1.concat(a2).forEach(function(obj) {
    hash.set(obj.id, Object.assign(hash.get(obj.id) || {}, obj))
});
var a3 = Array.from(hash.values());

ES6 對此進行了簡化:

let merge = (obj1, obj2) => ({...obj1, ...obj2});

注意重復的key會被合並,第二個對象的值優先,第一個對象的重復值會被忽略

示例:

let obj1 = {id: 1, uniqueObj1Key: "uniqueKeyValueObj1", repeatedKey: "obj1Val"};
let obj2 = {id: 1, uniqueObj2Key: "uniqueKeyValueObj2", repeatedKey: "obj2Val"};

merge(obj1, obj2)
// {id: 1, uniqueObj1Key: "uniqueKeyValueObj1", repeatedKey: "obj2Val", uniqueObj2Key: "uniqueKeyValueObj2"}
merge(obj2, obj1)
// {id: 1, uniqueObj2Key: "uniqueKeyValueObj2", repeatedKey: "obj1Val", uniqueObj1Key: "uniqueKeyValueObj1"}

完整的解決方案(與Lodash ,沒有下划線

var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]
var merge = (obj1, obj2) => ({...obj1, ...obj2});
_.zipWith(a1, a2, merge)
(2) [{…}, {…}]
   0: {id: 1, name: "test", count: "1"}
   1: {id: 2, name: "test2", count: "2"}

如果您有一組要合並的數組,您可以這樣做:

var arrayOfArraysToMerge = [a1, a2, a3, a4]; //a3 and a4 are arrays like a1 and a2 but with different properties and same IDs.
_.zipWith(...arrayOfArraysToMerge, merge)
(2) [{…}, {…}]
   0: {id: 1, name: "test", count: "1", extra1: "val1", extra2: 1}
   1: {id: 2, name: "test2", count: "2", extra1: "val2", extra2: 2}

減少版本。

var a3 = a1.concat(a2).reduce((acc, x) => {
    acc[x.id] = Object.assign(acc[x.id] || {}, x);
    return acc;
}, {});
_.values(a3);

我認為這是函數式語言的常見做法。

lodash 實現:

var merged = _.map(a1, function(item) {
    return _.assign(item, _.find(a2, ['id', item.id]));
});

結果:

[  
   {  
      "id":1,
      "name":"test",
      "count":"1"
   },
   {  
      "id":2,
      "name":"test2",
      "count":"2"
   }
]

已經有很多很好的答案,我將添加另一個來自我昨天需要解決的實際問題的答案。

我有一組帶有用戶 ID 的消息,還有一組包含用戶名和其他詳細信息的用戶。 這就是我設法將用戶詳細信息添加到消息的方式。

var messages = [{userId: 2, content: "Salam"}, {userId: 5, content: "Hello"},{userId: 4, content: "Moi"}];
var users = [{id: 2, name: "Grace"}, {id: 4, name: "Janetta"},{id: 5, name: "Sara"}];

var messagesWithUserNames = messages.map((msg)=> {
  var haveEqualId = (user) => user.id === msg.userId
  var userWithEqualId= users.find(haveEqualId)
  return Object.assign({}, msg, userWithEqualId)
})
console.log(messagesWithUserNames)

香草JS解決方案

const a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
const a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]

const merge = (arr1, arr2) => {
  const temp = []

  arr1.forEach(x => {
    arr2.forEach(y => {
      if (x.id === y.id) {
        temp.push({ ...x, ...y })
      }
    })
  })

  return temp
}

console.log(merge(a1, a2))

一個有效的 TypeScript 版本:

export default class Merge {
  static byKey(a1: any[], a2: any[], key: string) {
    const res = a1.concat(a2).reduce((acc, x) => {
      acc[x[key]] = Object.assign(acc[x[key]] || {}, x);
      return acc;
    }, {});

    return Object.entries(res).map(pair => {
      const [, value] = pair;
      return value;
    });
  }
}

test("Merge", async () => {
  const a1 = [{ id: "1", value: "1" }, { id: "2", value: "2" }];
  const a2 = [{ id: "2", value: "3" }];

  expect(Merge.byKey(a1, a2, "id")).toStrictEqual([
    {
      id: "1",
      value: "1"
    },
    { id: "2", value: "3" }
  ]);
});

const a3 = a1.map(it1 => {
   it1.test = a2.find(it2 => it2.id === it1.id).test
   return it1
 })

試試這個

var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]
let arr3 = a1.map((item, i) => Object.assign({}, item, a2[i]));

console.log(arr3);

想添加這個來自上面@daisihi 答案的答案。 主要區別在於這使用了擴展運算符。 此外,最后我刪除了 id,因為它首先是不可取的。

const a3 = [...a1, ...a2].reduce((acc, x) => {
   acc[x.id] = {...acc[x.id] || {}, ...x};
   return acc;
}, {});

這部分摘自另一個帖子。 從數組中的對象列表中刪除屬性

const newArray = Object.values(a3).map(({id, ...keepAttrs}) => keepAttrs);

這個怎么樣?

const mergeArrayObjects = (arr1: any[], arr2: any[], mergeByKey: string): any[] => {
  const updatedArr = [];
  for (const obj of arr1) {
    const arr1ValueInArr2 = arr2.find(
      a => a[mergeByKey] === obj[mergeByKey],
    );
    if (arr1ValueInArr2) {
      updatedArr.push(Object.assign(obj, arr1ValueInArr2));
    } else {
      updatedArr.push(obj);
    }
  }
  const mergeByKeyValuesInArr1 = arr1.map(a => a[mergeByKey]);
  const remainingObjInArr2 = arr2.filter(a => !mergeByKeyValuesInArr1.includes(a[mergeByKey]) )
  return updatedArr.concat(remainingObjInArr2)
}

您可以像這樣編寫一個簡單的對象合並函數

function mergeObject(cake, icing) {
    var icedCake = {}, ingredient;
    for (ingredient in cake)
        icedCake[ingredient] = cake[ingredient];
    for (ingredient in icing)
        icedCake[ingredient] = icing[ingredient];
    return icedCake;
}

接下來,您需要使用雙循環將其應用於您的數據結構

var i, j, a3 = a1.slice();
for (i = 0; i < a2.length; ++i)                // for each item in a2
    for (j = 0; i < a3.length; ++i)            // look at items in other array
        if (a2[i]['id'] === a3[j]['id'])       // if matching id
            a3[j] = mergeObject(a3[j], a2[i]); // merge

您也可以通過將一個參數作為空對象傳遞來使用mergeObject作為一個簡單的克隆。

如果您在兩個數組中具有相同 id 的完全相同數量的項目,您可以執行類似的操作。

const mergedArr = arr1.map((item, i) => {
  if (item.ID === arr2[i].ID) {
    return Object.assign({}, item, arr2[i]);
  }
});
function mergeDiffs(Schedulearray1, Schedulearray2) {
    var secondArrayIDs = Schedulearray2.map(x=> x.scheduleid);
    return Schedulearray1.filter(x=> !secondArrayIDs.includes(x.scheduleid)).concat(Schedulearray2);   
}
function arrayUnique(array) {
    var a = array.concat();
    for (var i = 0; i < a.length; ++i) {
        for (var j = i + 1; j < a.length; ++j) {
            if (a[i] === a[j])
            a.splice(j--, 1);
        }
    }
    return a;
}

他們都沒有為我工作。 我自己寫的:

const formatteddata=data.reduce((a1,a2)=>{

for (let t=0; t<a1.length; t++)
    {var id1=a1[t].id
            for (let tt=0; tt<a2.length; tt++)
                {var id2=a2[tt].id
                    if(id1==date2)
                      {a1[t]={...a1[t],...a2[tt]}}
                }
    }
return a1

})

適用於數組中任意數量的對象數組,具有不同的長度並且不總是一致的日期

暫無
暫無

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

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