0

I have a JSON array like:

var data = {
  name: 'Mike',
  level: 1,
  children: [
    { name: 'Susan',
      level: 2,   },
    { name: 'Jake',
      level: 2    },
    { name: 'Roy',
      level: 2 },
    ]
  }

How could i add a children array to Jake so that the array would then look like:

var data = {
  name: 'Mike',
  level: 1,
  children: [
    { name: 'Susan',
      level: 2,   },
    { name: 'Jake',
      level: 2,
      children: [ 
             { name: 'Angela',
               level: 3 }   
                ] 
    },
    { name: 'Roy',
      level: 2 },
    ]
  }
0

2 Answers 2

3

That's not JSON, that's a Javascript object. JSON is a text format for representing data.

First you would need to find Jake. He is in the data.children array, so look there:

var i = 0;
while (data.children[i].name != 'Jake') i++;

(That code assumes that Jake is actually somewhere in the array.)

Now you can add a property to the object, which is an array of objects:

data.children[i].children = [ 
  { name: 'Angela', level: 3 }   
];
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to accomplish the code data.children[i].children = [ { name: 'Angela', level: 3 } ]; with the push function ?
@rage: First you need the property to be an array: data.children[i].children = [];. Then you can push objects into it: data.children[i].children.push({ name: 'Angela', level: 3 });.
0
data.children[1].children = [{name: 'Angela',level: 3 }]

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.