英文:
Convert JsonObject into 'Node' type
问题
I have a json object.
{
"aaa": {
"aa": {
"xxx": {
"xxxx": {}
}
},
"ab": {
"xxx": {},
"xxxx": {
"xxxx": {}
},
"yyy": {
"yyyy": {},
"zzzz": {},
"kkkk": {}
}
}
},
"bbb": {
"": {}
}
}
In order to use react-checkbox-tree, I have to convert this object into node type.
const nodes = [{value: 'mars', label: 'Mars', children: [
{ value: 'phobos', label: 'Phobos' },
{ value: 'deimos', label: 'Deimos' },
],
}]
I have tried multiple recursive functions that suggested from stackoverflow, I couldn't find a solution.
英文:
I have a json object.
{
"aaa": {
"aa": {
"xxx": {
"xxxx": {}
}
},
"ab": {
"xxx": {},
"xxxx": {
"xxxx": {}
},
"yyy": {
"yyyy": {},
"zzzz": {},
"kkkk": {}
}
}
},
"bbb": {
"": {}
}
}
In order to use react-checkbox-tree,
I have to convert this object into node type.
const nodes = [{value: 'mars', label: 'Mars',children: [
{ value: 'phobos', label: 'Phobos' },
{ value: 'deimos', label: 'Deimos' },
],
}]`
I have tried multiple recursive functions that suggested from stackoverflow,
I couldn't find solution.
答案1
得分: 0
尝试这个递归代码段。
从一个空数组开始,对于当前对象的每个属性,创建一个新的值/标签对象并将其插入到数组中。
如果属性是一个对象,那么在该对象内创建一个名为 children
的新属性,并继续递归。
const a = {
"aaa": {
"aa": {
"xxx": {
"xxxx": {}
}
},
"ab": {
"xxx": {},
"xxxx": {
"xxxx": {}
},
"yyy": {
"yyyy": {},
"zzzz": {},
"kkkk": {}
}
}
},
"bbb": {
"": {}
}
}
const nodes = []
function buildNodesArray(jsonObject, children) {
Object.keys(jsonObject).forEach((item) => {
const obj = { value: item, label: item }
children.push(obj)
if (typeof jsonObject[item] === 'object' && jsonObject[item] !== null && Object.keys(jsonObject[item]).length > 0) {
obj.children = []
buildNodesArray(jsonObject[item], obj.children)
}
})
}
buildNodesArray(a, nodes)
console.log(nodes)
希望这对你有帮助。
英文:
Try this recursive snippet.
Start with an empty array and for each property of the current object, create a new value/label object and insert it into the array.
If the property is an object, then create a new property inside that object called children
and continue recursively
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const a = {
"aaa": {
"aa": {
"xxx": {
"xxxx": {}
}
},
"ab": {
"xxx": {},
"xxxx": {
"xxxx": {}
},
"yyy": {
"yyyy": {},
"zzzz": {},
"kkkk": {}
}
}
},
"bbb": {
"": {}
}
}
const nodes = []
function buildNodesArray(jsonObject, children) {
Object.keys(jsonObject).forEach((item) => {
const obj = { value: item, label: item }
children.push(obj)
if (typeof jsonObject[item] === 'object' && jsonObject[item] !== null && Object.keys(jsonObject[item]).length > 0) {
obj.children = []
buildNodesArray(jsonObject[item], obj.children)
}
})
}
buildNodesArray(a, nodes)
console.log(nodes)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论