我有以下輸入
[
{
"id": "abc",
"data1": 3,
"data2": "test1",
},
{
"id": "abc",
"data1": 4,
"data2": "test1",
},
{
"id": "xyz",
"data1": 2,
"data2": "test2",
}
]
我想決議這個串列,將 data1 轉換為串列并將具有相似 id 的所有 data1 添加到其中,如下所示以創建新串列。
[
{
"id": "abc",
"data1": [3,4],
"data2": "test1",
},
{
"id": "abc",
"data1": [2],
"data2": "test2",
}
]
我已經嘗試了幾種方法,比如使用 map/reduce,但我的解決方案都沒有奏效。
uj5u.com熱心網友回復:
const data = [
{
id: 'abc',
data1: 3,
data2: 'test1',
},
{
id: 'abc',
data1: 4,
data2: 'test1',
},
{
id: 'xyz',
data1: 2,
data2: 'test2',
},
];
/**
* To merge the array of objects by a key
*
* @param {any[]} objectArray The input object array
* @param {string} mergeBy The key for merging the objects
* @param {string} property The key to which the values should be aggregated
* @returns
*/
const groupBy = (objectArray, mergeBy, property) =>
Object.values(
objectArray.reduce(
(
/** @type {{ [x: string]: {}; }} */ acc,
/** @type {{ [x: string]: any; }} */ obj
) => {
const key = obj[mergeBy];
const curGroup = acc[key] ?? {};
// if the key is already exists in the accumulator object
if (curGroup?.[property] && obj?.[property]) {
curGroup[property].push(obj[property]);
return { ...acc, [key]: { ...curGroup } };
}
if (!curGroup?.[property] && obj?.[property]) {
const data = { ...obj } ;
data[property] = [];
data[property].push(obj[property]);
return { ...acc, [key]: { ...data } };
}
},
{}
)
);
groupBy(data, 'id', 'data1');
uj5u.com熱心網友回復:
感謝你的幫助。我已經使用以下邏輯解決了
let helper = {}
let result = labels.reduce(function(r, o) {
var key = o.id
var outputpDic = {
'id': o.id,
'data1': [o.data1],
'data2': o.data2,
}
if (!helper[key]) {
helper[key] = Object.assign({}, outputpDic)
r.push(helper[key])
} else {
helper[key].data1.push(o.data1)
}
return r
}, [])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/533374.html
