gpt4 book ai didi

javascript - 如何将数据从对象树转换为像这样的对象数组

转载 作者:行者123 更新时间:2023-11-29 16:30:45 25 4
gpt4 key购买 nike

我想将数据从对象树转换为此类对象数组

如果你能给我这个问题的算法或解决方案,我就无能为力。任何你可以捕获的想法。我的大脑拒绝工作。

来自:

const input = {
p1: {
s1: {
title: 'scene 1',
description: 'description 1',
value: 1,
},
s2: {
title: 'scene 2',
description: 'description 2',
value: 32,
},
s3: {
title: 'scene 3',
description: 'description 3',
value: 89,
},
s4: {
title: 'scene 3',
description: 'description 3',
value: 0,
},
},
p2: {
s5: {
title: 'scene 5',
description: 'description 5',
value: 0,
},
s6: {
title: 'scene 6',
description: 'description 6',
value: 42,
},
s7: {
title: 'scene 7',
description: 'description 7',
value: -9,
},
},
}

至:

[
{ projectId: 'p1', sceneId: 's1', value: 1, title: 'scene 1' },
{ projectId: 'p1', sceneId: 's2', value: 32, title: 'scene 2' },
{ projectId: 'p1', sceneId: 's3', value: 89, title: 'scene 3' },
{ projectId: 'p2', sceneId: 's6', value: 42, title: 'scene 6' },
]

我尝试使用 Object.entries 和 Array.reduce 以及递归函数来做到这一点,但我两天都做不到......:D

这就是我的尝试

const recursive = (obj, lvl = 0) => {
if (typeof obj !== 'object') {

}
const value = Object.entries(obj);

return value.reduce((acc, [key, value]) => {
if (typeof value !== 'object') {
return {...acc, [key]: value};
}
if (lvl === 0) {

return {...recursive(value, lvl + 1), sceneId: key };
}

}, {})
}



const transform = (data) => {

const a = Object.entries(data);
return a.reduce((acc, [key, value]) => {
return [...acc, recursive(value)];
}, [])

}

console.log(transform(input))

请帮忙。

最佳答案

您可以采用动态方法,通过传递嵌套对象所需的键和获取平面结果集的值键。

function getFlat(object, keys, values) {
function iter(object, [key, ...keys], temp = {}) {
if (key === undefined) {
if (object.value > 0) {
result.push(values.reduce((t, k) => ({ ...t, [k]: object[k] }), temp));
}
return;
}
Object.entries(object).forEach(([k, v]) => iter(v, keys, { ...temp, [key]: k }));
}

var result = [];
iter(object, keys);
return result;
}

var input = { p1: { s1: { title: 'scene 1', description: 'description 1', value: 1 }, s2: { title: 'scene 2', description: 'description 2', value: 32 }, s3: { title: 'scene 3', description: 'description 3', value: 89 }, s4: { title: 'scene 3', description: 'description 3', value: 0 } }, p2: { s5: { title: 'scene 5', description: 'description 5', value: 0 }, s6: { title: 'scene 6', description: 'description 6', value: 42 }, s7: { title: 'scene 7', description: 'description 7', value: -9 } } },
output = getFlat(input, ['projectId', 'sceneId'], ['value', 'title']);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何将数据从对象树转换为像这样的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58488402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com