Javascript:如何从对象数组动态创建深层嵌套的对象? 我可以实现一个级别的分离,但是代码变得相当复杂,无法找出如何实现第二个级别。
实际:
[{
brandId: 1,
spec_desc: "engines",
av: 3000
tv: 1000,
brandName: "bmw",
id: 1,
group: "cars",
cost: 20000.00,
currency: "USD",
desc: "manufacturing costs"
},
{
brandId: 1,
spec_desc: "brakes",
av: 1000,
tv: 2000,
brandName: "bmw",
id: 1,
....
},
{
brandId: 2,
spec_desc: "engines",
av: 1800,
tv: 2500,
brandName: "audi",
id: 2
....
}
]
预期:
[{
group: "cars",
id: 1,
brands: [{
brandId: 1,
brandName: "BMW",
specs: {
power: [{
spec_desc: "engines",
av: 3000,
tv: 1000
},
{
spec_desc: "brakes",
av: 1000,
tv: 2000
}
],
cost: {
desc: "manufacturing costs",
value: 20000.00,
currency: "USD"
}
}
},
{
brandId: 2,
brandName: "audi",
specs: {
power: [
...
],
}
}
]
},
group: "bikes",
id: 2,
brands: [
....
]
]
这是我尝试过的方法,但是只能在brandName达到一个级别之前获得分组。
function genrows(groups, groupKey) {
return _.toPairs(groups).map(([key, units]) => ({
[groupKey]: key,
units
}))
}
function gengroups(arr, iteratee, key) {
const grouped = _.groupBy(arr, iteratee)
return genrows(grouped, key)
}
function grouparray(units, props) {
let result = [{
units
}]
props.forEach((prop, i) => {
const key = prop
const iteratee = prop.iteratee || prop
result = _.flatten(
result.map(row => {
return gengroups(row.units, iteratee, key).map(group =>
// {...row, ...{ [key]: group[key], units: group.units }}
({ ...row,
[key]: group[key],
units: group.units
}),
)
}),
)
})
return _.flatten(result)
}
const groups = ['brandName', 'id'] //group by key names
// it fetches out these group tags to generate keys,
const desired = grouparray(actual, groups);
有人可以帮助我解决如何动态实现这一目标吗?如果您已经做到了这一点,非常感谢您抽出宝贵的时间阅读,即使您无法帮助。
PS:让我知道进一步的澄清,我的结果对象也使用了lodash函数。
答案 0 :(得分:0)
您可以采用经典的方法,即存储找到id
的最后一组并将该品牌与该对象分组。
var data = [{ brandId: 1, spec_desc: "engines", av: 3000, tv: 1000, brandName: "bmw", id: 1, group: "cars", cost: 20000.00, currency: "USD", desc: "manufacturing costs" }, { brandId: 1, spec_desc: "brakes", av: 1000, tv: 2000, brandName: "bmw" }, { brandId: 2, spec_desc: "engines", av: 1800, tv: 2500, brandName: "audi" }],
lastGroup,
result = data.reduce((r, { brandId, spec_desc, av, tv, brandName, id, group, cost: value, currency, desc }) => {
if (id !== undefined) r.push(lastGroup = { group, id, brands: [] });
var brand = lastGroup.brands.find(q => q.brandId === brandId);
if (!brand) lastGroup.brands.push(brand = { brandId, brandName, specs: { power: [], cost: { desc, value, currency } } });
brand.specs.power.push({ spec_desc, av, tv });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }