gpt4 book ai didi

javascript - 展平分层数据

转载 作者:搜寻专家 更新时间:2023-11-01 05:04:49 24 4
gpt4 key购买 nike

我有这样的数据结构:

{
name: 'test',
config: { ... },
prev: {
name: 'test1.1',
config: { ... },
prev: {
name: 'test1.1.1',
config: { ... },
prev: {
name: 'test1.1.1.1',
config: { ... },
prev: undefined
}
}
}
}

该结构可以在“prev”对象中包含任意数量的递归但相同的结构。

我想提取每个 child 的“姓名”属性。我如何使用下划线将其展平以生成如下结果集:

['test', 'test1.1', 'test1.1.1', 'test1.1.1.1']

如果扁平化过程可以返回类似的东西,那就更好了

[
{name: 'test', config: { ... }},
{name: 'test1.1', config: { ... }},
{name: 'test1.1.1', config: { ... }},
{name: 'test1.1.1.1', config: { ... }}
]

我目前的解决方案是这样的(这不是最优的。我想使用一个 _.chain 来生成它):

var _self = {
flatten: function (obj) {
var map = [];
return _self.flattenRecurse(obj, map);
},
flattenRecurse: function (obj, map) {
map.push({name: obj.name, config: obj.config});
if (obj.prev) {
_self.flattenRecurse(obj.prev, map);
}
}
}
var flattened = _self.flatten(data);

最佳答案

像这样使用纯js更容易

const data = {
name: 'test',
config: { },
prev: { name: 'test1.1',
config: { },
prev: {
name: 'test1.1.1',
config: { },
prev: { name: 'test1.1.1.1', config: { }, prev: undefined }
}
}
};

function flatten (data) {
let result = [];

while (data) {
result.push({ name: data.name, config: data.config });
data = data.prev;
}

return result;
}

console.log(flatten(data));

// get only names
const res = flatten(data).map(el => el.name);
console.log(res);

关于javascript - 展平分层数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28453824/

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