[英]Convert an array of objects to a single object
我有一個數組:
[
{
path: 'default',
moduleName: 'asset',
masterName: 'assetType',
data: [ { "code":"mov, "name":"Movable"} ]
},
{
path: 'default',
moduleName: 'common-master',
masterName: 'city',
data: [ { "code":"ind.ka.blr, "name":"Bangalore"},
{ "code":"ind.ka.mys, "name":"Mysore"}] ,
{
path: "default",
moduleName: "common-master",
masterName: "country",
code:""
}
]
我想在 javascript 中構造一個對象:
Res: {
Mdms: {
default: {
asset: { assetType: [ { "code":"mov, "name":"Movable"} ] },
common-master: { city: [ { "code":"ind.ka.blr, "name":"Bangalore"},
{"code":"ind.ka.mys, "name":"Mysore"}],
country: [ {"code": "ind", "name": "India"},
{ "code": "usa", "name": "United States of America"},
{ "code": "aus", "name": "Australia" },
{"code": "can", "name": "Canada"}]
}
}
}
}
我嘗試了 reduce 方法,但它沒有生成所需的輸出。
ResInfo = finalArray.reduce((ResInfo, arr) => {
ResInfo[arr.path] = (ResInfo[arr.moduleName] || []).concat(arr);
})
提前致謝!
您應該為此使用 reduce 函數,但您需要進行一些更改。 您可以在此處閱讀有關 reduce 的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
// reduce takes as first argument an accumulator (your result) and the current element.
// what you will return will become the new accumulator
finalArray => finalArray.reduce((acc, el) => {
const path = acc[el.path] || {};
const moduleName = path[el.moduleName] || {};
const masterName = moduleName[el.masterName] || [];
return ({
...acc,
// we merge the path of this object with the accumulator
[el.path]: {
...path,
// we merge the modulename of this object with the accumulator
[el.moduleName]: {
...moduleName,
// we merge the data array of this object with the accumulator
[el.masterName]: [
...masterName,
...el.data
]
}
}
});
}, {});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.