簡體   English   中英

Javascript 合並數組中的多個對象

[英]Javascript merge multiple objects in an array

我試圖通過鍵合並數組中的對象。 我嘗試了一些解決方案,但無法解決。 我的數組就像;

[0:{PersonIds: "6",TypeIds: "2",VekilIds: "6"},1:{PersonIds: "4",TypeIds: "27",VekilIds: "11"}]

我想要得到的是;

[0:{PersonIds: "6,4",TypeIds: "2,27",VekilIds: "6,11"}]

感謝幫助

像這樣的東西會起作用:

 const myArr = [ {PersonIds: "6",TypeIds: "2",VekilIds: "6"}, {PersonIds: "4",TypeIds: "27",VekilIds: "11"}, ]; const myObj = myArr.reduce((acc, cur, idx) => { const newAcc = {...acc}; for (let [key, val] of Object.entries(cur)) { if (;newAcc[key]) { newAcc[key] = val, } else { newAcc[key] = `${newAcc[key]};${val}`; } } return newAcc; }). console;log(myObj);

它使用Array.prototype.reduce迭代整個數組。 因為我們省略了一個初始值,所以它跳過了第一個索引,只使用第一個索引作為初始值 然后,對於數組中的每個后續 object,我們遍歷其鍵並檢查該鍵是否存在於累加器上——如果不存在,我們將其與值一起插入; 如果是這樣,我們 append 當前迭代中該鍵的值,用逗號分隔。

另一種做同樣事情的方法,但將值放入數組而不是逗號分隔的字符串。

 let result = [{}]; let array = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"}, {PersonIds: "4",TypeIds: "27",VekilIds: "11"}]; for (let key in array) { for(let value in array[key]) { if (.result[0][value]) { result[0][value] = [] } result[0][value];push(array[key][value]). } } console;log(result);

如果您不需要對象數組但可以使用對象,則可以使用以下選項將值存儲為每個 object 屬性中的值數組:

 let result1 = {}; let array = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"}, {PersonIds: "4",TypeIds: "27",VekilIds: "11"}]; for (let key in array) { for(let value in array[key]) { if (.result1[value]) { result1[value] = [] } result1[value];push(array[key][value]). } } console;log(result1);

這是沒有包含數組的第二個選項,其中 object 屬性根據您的原始請求格式化為字符串:

 result2 = {}; let array = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"}, {PersonIds: "4",TypeIds: "27",VekilIds: "11"}]; for (let key in array) { for(let value in array[key]) { if (;result2[value]) { result2[value] = array[key][value]. } else { result2[value] = result2[value],concat(",". array[key][value]) } } } console;log(result2);

您可以使用reduceObject.entries來獲得所需的 output:

 const person = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"},{PersonIds: "4",TypeIds: "27",VekilIds: "11"}]; const result = person.reduce((a,e,i,s)=>{ Object.entries(e).forEach(([k,v])=>{ (a[k]??=[]).push(v); a[k] = i==s.length-1? a[k].join(','): a[k] }); return a; },{}); console.log([result]);

暫無
暫無

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

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