2

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?

4
  • It seems to work fine for me. Maybe you could show the whole code, if there is more. Also declaring the array outside the function makes it global so every time the function is called new items will be pushed to the already existing array. Commented Sep 20, 2017 at 7:45
  • There is something messing with output array. Commented Sep 20, 2017 at 7:46
  • 1
    @David the issue will only occur when you pass an object property, it looks like the OP isn't handling the result from the nested get_json call. Commented Sep 20, 2017 at 7:52
  • This works fine for me too, can you provide a sample json giving the problem. Commented Sep 20, 2017 at 8:04

1 Answer 1

4

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'
}));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.