gpt4 book ai didi

javascript - JSON 对象 - 递归地更改所有子项的属性名称

转载 作者:行者123 更新时间:2023-12-03 07:47:19 27 4
gpt4 key购买 nike

我有以下 json 对象。

myJsonObj = {  
"name":"Laptop",
"type":"hardware computer laptop",
"forward":[
{
"name":"Depends On",
"forward":[
{
"name":"test asset 1",
"type":"hardware",
"link":"somelink"
}
]
},
{
"name":"somename",
"forward":[
{
"name":"test asset 5",
"type":"hardware",
"link":"somelink"
}
]
}
],
"inverse":[
{
"name":"somename",
"inverse":[
{
"name":"test asset 4",
"ciTypeCls":"hardware",
"link":"somelink"
},
{
"name":"test asset 1",
"ciTypeCls":"hardware",
"link":"somelink"
}
]
},
{
"name":"somename",
"inverse":[
{
"name":"test asset 1",
"ciTypeCls":"hardware",
"link":"somelink"
}
]
}
]
}

我正在尝试将属性名称 forward 更改为 children

以下是我的代码

myJsonObj = {
"name": "Laptop",
"type": "hardware computer laptop",
"forward": [{
"name": "Depends On",
"forward": [{
"name": "test asset 1",
"type": "hardware",
"link": "somelink"
}]
}, {
"name": "somename",
"forward": [{
"name": "test asset 5",
"type": "hardware",
"link": "somelink"
}]
}],
"inverse": [{
"name": "somename",
"inverse": [{
"name": "test asset 4",
"ciTypeCls": "hardware",
"link": "somelink"
}, {
"name": "test asset 1",
"ciTypeCls": "hardware",
"link": "somelink"
}]
}, {
"name": "somename",
"inverse": [{
"name": "test asset 1",
"ciTypeCls": "hardware",
"link": "somelink"
}]
}]
}

jQuery.each(myJsonObj, function(e) {
e.children = e.forward;
delete e.forward;
});

console.log(myJsonObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

它似乎不起作用,我做错了什么?

最佳答案

试试这个:

 jQuery.each(myJsonObj.forward, function(i , item) {
//Nested forward
item.children = item.forward;
delete item.forward;
});
//PARENT forward
myJsonObj.children = myJsonObj.forward;
delete myJsonObj.forward;

JSFiddle https://jsfiddle.net/xbkp10Ly/

关于javascript - JSON 对象 - 递归地更改所有子项的属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35150301/

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