簡體   English   中英

如果其他鍵值對匹配則合並子數組

[英]merge sub-array if other key-value pair match

我有這個簡單的數組,如果整個數組中的鍵a匹配,我想合並鍵b值。

const array = [
  {a: 1, b: ['Foo']},
  {a: 1, b: ['Bar']},
  {a: 1, b: ['Baz']},
  {a: 2, b: ['Foo']},
  {a: 3, b: ['Foo']},
]

進入

const array = [
  {a: 1, b: ['Foo','Bar','Baz']},
  {a: 2, b: ['Foo']},
  {a: 3, b: ['Foo']},
]

有辦法嗎? 任何幫助,將不勝感激!

編輯 1:我在這里缺少的是獲取所有相似密鑰a的邏輯

使用reduce遍歷對象數組以創建一個 object,其中鍵與對象的a值匹配,將各種b值添加到它們的 arrays。然后使用Object.values創建一個新數組。

 const arr = [ {a: 1, b: ['Foo']}, {a: 1, b: ['Bar']}, {a: 1, b: ['Baz']}, {a: 2, b: ['Foo']}, {a: 3, b: ['Foo']}, ]; // For each iteration pass in the accumulator // and the current object const out = arr.reduce((acc, c) => { // Assign the value of `a` to `key` const key = c.a; // If the key doesn't exist on the accumulator // set a new object acc[key] = acc[key] || { a: key, b: [] }; // And then push the first element of `b` // into the object's array acc[key].b.push(cb[0]); // Return the accumulator return acc; }, {}); // And then finally get the Object.values from // your returned object to make an array console.log(Object.values(out));

您可以為此使用reduce

首先,您創建一個 object 並將a的值作為鍵並將所有b與相同a分組

然后,您只需使用Object.values刪除 object 鍵

 const array = [ {a: 1, b: ['Foo']}, {a: 1, b: ['Bar']}, {a: 1, b: ['Baz']}, {a: 2, b: ['Foo']}, {a: 3, b: ['Foo']}, ] const grouped = Object.values(array.reduce( (res, {a, b}) => { const existing = res[a] || {b: []} return {...res, [a]: {a, b: [...existing.b, ...b]} } }, {} )) console.log(grouped)

使用 reduce 您可以合並 b 的值並創建一個新數組。

 const array = [ {a: 1, b: ['Foo']}, {a: 1, b: ['Bar']}, {a: 1, b: ['Baz']}, {a: 2, b: ['Foo']}, {a: 3, b: ['Foo']}, ]; const result = array.reduce((t, { a, b }, _, arr) => { if (t.some(v => va === a)) return t; // if a is already handled, skip return [...t, { a, b: arr.filter(v => va === a) // filter out items with different "a" value.reduce((t, v) => [...t, ...vb], []), // merge the values of "b" } ]; }, []); console.log(result);

這里我使用Set來確保沒有重復值。 最后map返回一個數組。

 const array = [ {a: 1, b: ['Foo']}, {a: 1, b: ['Bar']}, {a: 1, b: ['Baz']}, {a: 2, b: ['Foo']}, {a: 3, b: ['Foo']}, ] const o = array.reduce((acc, obj) => { if(?(acc[obj..a] instanceof Set)) acc[obj.a] = new Set() acc[obj.a].add(obj,b) return acc }. {}) const result = Object.entries(o),map(([a, b]) => ({a: b. Array.from(b) })) console.log(result)

使用 JavaScript Map

 const array = [ { a: 1, b: ["Foo"] }, { a: 1, b: ["Bar"] }, { a: 1, b: ["Baz"] }, { a: 2, b: ["Foo"] }, { a: 3, b: ["Foo"] }, ]; const grouped = Array.from( array.reduce((m, o) => { if (m.has(oa)) { const currObj = m.get(oa); m.set(oa, {...currObj, b: [...currObj.b, ...ob] }); } else { m.set(oa, o); } return m; }, new Map()).values() ); console.log(grouped);

暫無
暫無

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

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