gpt4 book ai didi

javascript - 如何使用子嵌套迭代嵌套对象键

转载 作者:行者123 更新时间:2023-12-04 14:54:27 25 4
gpt4 key购买 nike

我想迭代嵌套的对象键,它们也将嵌套内部子对象:

嵌套对象代码:

{
"F2C3C496-BEA6-A5E8-15F0-E2867304B463": {
"D39FD497-9529-6CC3-70DE-E8D9277C18D3": {
"child": {
"87A1817D-CFA9-70FD-131B-224658AF13CE": {
"next": {
"F7A90266-B7F4-4CC2-0F1B-D4B320E2EC1A": {}
}
}
},
"next": {
"B49927ED-369E-E219-FC1A-8E4BAAFC3933": {
"next": {}
}
}
}
}
}

要迭代的 JS 代码:

flowThrough = (obj, callback, context?, path?: string) => {
let nestedKey=';'
Object.keys(obj).forEach(key => {
if(!isEmptyObject(key))
callback(key, context, path);

if (!isEmpty(obj[key]) && typeof obj[key] === 'object') {
if(obj[key].hasOwnProperty('next'))
nestedKey = obj[key].next;
else if(obj[key].hasOwnProperty('child'))
nestedKey = obj[key].child;
else nestedKey = obj[key];

this.flowThrough(nestedKey, callback, context, (path)? has(context, path.concat(".next"))?path.concat(`.next[${get(context, path.concat(".next").length)}]`): path.concat('.').concat("next[0]") : key)
}
})
}

实际上,上面的代码在一个嵌套级别上工作以获取 key (id)。如果它到达空对象键,则循环到此结束。实际上,它应该检查任何其他 child /下一个是否存在。

预期输出:

{  "flow": [
{
"id": "F2C3C496-BEA6-A5E8-15F0-E2867304B463",
"next": [
{
"id": "D39FD497-9529-6CC3-70DE-E8D9277C18D3",
"child": [
{
"id": "87A1817D-CFA9-70FD-131B-224658AF13CE",
"next": [
{
"id": "F7A90266-B7F4-4CC2-0F1B-D4B320E2EC1A",
"next": []
}
]
}
],
"next": [
{
"id": "B49927ED-369E-E219-FC1A-8E4BAAFC3933",
"next": []
}
]
}
]
}
]
}

请给我解决方案。

最佳答案

let obj = {
"F2C3C496-BEA6-A5E8-15F0-E2867304B463": {
"D39FD497-9529-6CC3-70DE-E8D9277C18D3": {
"child": {
"87A1817D-CFA9-70FD-131B-224658AF13CE": {
"next": {
"F7A90266-B7F4-4CC2-0F1B-D4B320E2EC1A": {}
}
}
},
"next": {
"B49927ED-369E-E219-FC1A-8E4BAAFC3933": {
"next": {}
}
}
}
}
}
const setObj = e => {
let tmp = {}
if (Array.isArray(e[0])) e = e[0]
if (typeof e[0] === 'string' && e[0].split('-').length === 5) {
tmp = {
id: e[0],
next: setObj(Object.entries(e[1]))
};
} else if (e[1]) {
tmp = {
child: setObj(Object.entries(e[1]))
};
}
return tmp
}
let newobj = Object.entries(obj).map(setObj)[0]
console.log(newobj)

原始答案...这是一种解决方法。将递归函数与 Object.entries 一起使用收集数据。我发现结果是一系列嵌套的 id 数组 - 所以我用 join() 将它们全部展平,然后再次拆分它们。最后,filter() 帮助移除空数组索引

let obj = {
"F2C3C496-BEA6-A5E8-15F0-E2867304B463": {
"D39FD497-9529-6CC3-70DE-E8D9277C18D3": {
"child": {
"87A1817D-CFA9-70FD-131B-224658AF13CE": {
"next": {
"F7A90266-B7F4-4CC2-0F1B-D4B320E2EC1A": {}
}
}
},
"next": {
"B49927ED-369E-E219-FC1A-8E4BAAFC3933": {
"next": {}
}
}
}
}
}
const getKeys = e => {
let ret = []
if (e[0].split('-').length === 5) ret.push(e[0]);
if (e[1]) ret.push(Object.entries(e[1]).map(getKeys))
return ret.join(',')
}
let keys = Object.entries(obj).map(getKeys)[0].split(",").filter(e => e)
console.log(keys)

关于javascript - 如何使用子嵌套迭代嵌套对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68366351/

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