gpt4 book ai didi

javascript - 如何在 Javascript 中进入 n 维对象数组?

转载 作者:行者123 更新时间:2023-12-02 18:44:17 25 4
gpt4 key购买 nike

我有一个 n 维的对象数组,n 未知。这是数据示例:

Data = [{"value":{"Id":"1","Text":"abcd","Parent":""},"children":[{"value":{"Id":"2","Text":"abcd","Parent":"1"},"children":[{"value":{"Id":"3","Text":"abcd","Parent":"1"},"children":[{"value":...

我想遍历所有这个数组来读取对象数据。我怎样才能用 JavaScript 做到这一点?

最佳答案

使用递归,假设你想要的只是值,使用这样的东西

var data = [
{
"value": {
"Id": "1",
"Text": "abcd",
"Parent": ""
},
"children": [
{
"value": {
"Id": "2",
"Text": "abcd",
"Parent": "1"
},
"children": [
{
"value": {
"Id": "3",
"Text": "abcd",
"Parent": "1"
}
}
]
}
]
}
];

function travel(data){
for(var i =0;i< data.length;++i){
if(data[i].hasOwnProperty('value')){
console.log('Value: ',data[i].value);
}
if(data[i].hasOwnProperty('children')){
travel(data[i].children);
}
}
}

function collect(data) {
var res= [];
function travelAux(data){
for(var i =0;i< data.length;++i){
if(data[i].hasOwnProperty('value')){
res.push(data[i].value);
}
if(data[i].hasOwnProperty('children')){
travelAux(data[i].children);
}
}
}
travelAux(data);
return res;
}
travel(data);

关于javascript - 如何在 Javascript 中进入 n 维对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560796/

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