gpt4 book ai didi

javascript - 如何使用lodash将键值对添加到树结构对象

转载 作者:行者123 更新时间:2023-11-30 19:28:02 29 4
gpt4 key购买 nike

我需要像 json 对象一样在树的末尾添加键值对。

[{
"name": "minpur",
"children": [{
"name": "ppp1",
"children": [{
"name": "feeder",
"children": [{
"name": "rmu16",
"children": [{
"name": "invt16",
"children": [{
"aname": "inv 01"
}]
}]
}]
}]
}]
}]

预期

[{
"name": "minpur",
"children": [{
"name": "ppp1",
"children": [{
"name": "feeder",
"children": [{
"name": "rmu16",
"children": [{
"name": "invt16",
"children": [{
"aname": "inv 01",
**
"value": 300 **
}]
}]
}]
}]
}]
}]

试过递归函数如下

let traverse = function(jsonObj) {
if (jsonObj !== null && typeof jsonObj == "object") {
return Object.entries(jsonObj).forEach(([key, value]) => {
if (key != "aname") {
traverse(value);
} else {
return value;
}
});
}
}

最佳答案

检查对象上是否存在 aname 键,如果存在则添加该属性。如果它不使用 Array.forEach() 迭代子项,并在子项上调用遍历。

const traverse = (key, value) => obj => {
const inner = obj => {
if(obj.hasOwnProperty(key)) obj.value = value
else obj.children.forEach(inner)
}

return inner(obj)
}

const tree = [{"name":"minpur","children":[{"name":"ppp1","children":[{"name":"feeder","children":[{"name":"rmu16","children":[{"name":"invt16","children":[{"aname":"inv 01"}]}]}]}]}]}]

tree.forEach(traverse('aname', 300))

console.log(tree)

关于javascript - 如何使用lodash将键值对添加到树结构对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56714580/

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