我有json内部属性“Steps”。内在的“步骤”我有一个新的属性“步骤”。和infiniti ..如何编写函数,foreach所有“steps”属性并将start_location和end_location推送到myArr。
我可以通过forEach编写代码,但我不认为这是正确的。
请?帮助
{
[
{
"start_location": {
"lat": 55.757394599999998,
"lng": 37.6325626
},
"end_location": {
"lat": 55.736126800000001,
"lng": 37.592756799999997
},
"steps": [
{
"start_location": {
"lat": 55.757394599999998,
"lng": 37.6325626
},
"end_location": {
"lat": 55.757203399999987,
"lng": 37.631541800000001
},
"steps": [
{
"start_location": {
"lat": 55.757205778493002,
"lng": 37.631539696071997
},
"end_location": {
"lat": 55.735556776788997,
"lng": 37.594390710771997
},
"steps": [
{
"start_location": {
"lat": 55.757205778493002,
"lng": 37.631539696071997
},
"end_location": {
"lat": 55.735556776788997,
"lng": 37.594390710771997
},
},
{
"start_location": {
"lat": 55.757205778493002,
"lng": 37.631539696071997
},
"end_location": {
"lat": 55.735556776788997,
"lng": 37.594390710771997
},
},
]
},
......
]
},
....
]
}
]
}
答案 0 :(得分:1)
考虑这个简单的功能:
function enumerate(x, fn) {
if (x && typeof x === 'object') {
for (let val of Object.values(x)) {
fn(val);
enumerate(val, fn);
}
}
}
它遍历一个嵌套的对象结构,并为它找到的每个值调用给定的回调(无论是对象还是原语)。您可以将它应用于您的结构并提供分析值的回调,如果它具有所需的属性,则将其添加到数组中,例如:
enumerate(yourData, function (val) {
if (val.start_location)
yourArray.push([val.start_location, val.end_location])
});
希望这有助于您入门,祝您好运!