我有相当对称的数据,我想减少:
const data = [
{
name: 'Bob',
relations: {
siblings: [
{
name: 'Tom',
age: '20'
},
{
name: 'Jacob'
}
]
}
},
{
name: 'Robert',
relations: {
siblings: [
{
name: 'Timmy',
age: '16'
}
]
}
}
];
我想要生产什么:
const output = {
name: ['Bob', 'Robert'],
relations: {
siblings: {
name: ['Tom', 'Jacob', 'Timmy'],
age: ['20', '16']
}
}
}
我知道如何在不使用递归的情况下做到这一点,但我想要一个深入的解决方案。 通常我只是使用 reduce 和递归,但后来我意识到我必须将值添加到对象的当前级别,但我不知道该怎么做。
const compact = (value) => {
if (typeof value === 'string') {
return { [value]: '' }; // turning into an object for the mean time
}
if (Array.isArray(object)) { }
// if object
return Object.entries(object).reduce((accum, [key, value]) => {
// Do I have to pass accum[key] into compact here? Is this the correct way to do this?
accum[key] = compact(value);
return accum;
}, {});
};
通过仅具有像
relations.siblings
这样的固定属性,您可以采取动态方法并仅移交获得扁平结构的目标。
const
data = [{ name: 'Bob', relations: { siblings: [{ name: 'Tom', age: '20' }, { name: 'Jacob' }] } }, { name: 'Robert', relations: { siblings: [{ name: 'Timmy', age: '16' }] } }],
getData = (array, target = {}) => {
for (const { relations, ...rest } of array) {
Object
.entries(rest)
.forEach(([k, v]) => (target[k] ??= []).push(v));
if (relations) getData(relations.siblings, (target.relations ??= {}).siblings ??= {});
}
return target;
},
result = getData(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }