如何在Javascript中进入n维对象数组? [英] How to travel into n dimensional object array in Javascript?
本文介绍了如何在Javascript中进入n维对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个n维n的对象数组是未知的。
以下是数据示例:
I have an object array with n dimensions by n is unknown. Here is the example of data :
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中做到这一点?
I'd like to travel inside all this array to read the object data. How could I do that in javascript?
推荐答案
使用递归,假设你想要的只是值使用这样的东西
Use recursion, assuming all you want is value use something like this
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中进入n维对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文