Reputation: 1552
I have a function that's supposed to loop through a JSON file, get the values and push them to a new array.
I have declared the array outside the function as follows :
var output = [];
function get_json(jsonObj) {
console.log("Out put => " + output);
for (var x in jsonObj) {
if (typeof (jsonObj[x]) == 'object') {
get_json(jsonObj[x]);
} else {
output.push({
key: x,
value: jsonObj[x]
});
//console.log(output);
}
}
return output;
}
The above function is called and passed into the json data as follows :
var result = get_json(jsonObj);
Which is supposed to return an array with values, a key, and a value. However, when I push data to the function, I get the output variable to be undefined so it cannot create an array, leading to a failure. How can I declare the array ? And what is the best position to declare it?
Upvotes: 2
Views: 586
Reputation: 5323
You're trying to do a recursive function. You can move output
declaration inside the function and return it in the end, but don't forget to populate it on every iteration (ie. using concat
and push
here). I prefer this version over the global variable since it's cleaner and avoids conflicts like you seem to have.
function get_json(jsonObj) {
var output = [];
for (var x in jsonObj) {
if (typeof(jsonObj[x]) === 'object') {
output = output.concat(get_json(jsonObj[x]));
} else {
output.push({
key: x,
value: jsonObj[x]
});
}
}
return output;
}
console.log(get_json({
person: {
name: 'John Doe',
age: 26,
stuff: [{
name: 'Big Sword'
},
{
name: 'Yoyo'
}
]
},
city: 'New York'
}));
Upvotes: 4