0

How can I create an json format in javascript

var data = [
     {
         label: 'node1',
         children: [
             { label: 'child1' },
             { label: 'child2' }
         ]
     },
     {
         label: 'node2',
         children: [
             { label: 'child3' }
         ]
     }
    ]

I can add the 'node' using data.push, but how to proceed with childrens? Thank's!

4
  • you need some reference to the pushed object. Commented Apr 18, 2016 at 9:18
  • Hello Mihai! Can you clarify what you are trying to do? It's a bit unclear. Commented Apr 18, 2016 at 9:22
  • I have a list of users with 2 different type of id, first one is 9 digit length and second it's 13. I want to create a json (in the format i have specified) where i have id with 9 digit as parent and id with 13 digit as children. Commented Apr 18, 2016 at 9:29
  • You should use data[i].children.push(...), however you need to determine an appropriate value for i so that it is appended to the correct children array. Commented Apr 18, 2016 at 9:46

1 Answer 1

1

First off, there is no such thing as a JSON array. You are working with an array. JSON is a way to transfer data between systems.

You have an array called data that you need to push an object into...

so something like:

data.push({
    label: 'node3',
    children: [
        { label: 'child3' },
        { label: 'child3' }
     ]
});

Now.. you've got a problem at this point, because you are duplicating the label property, which is not allowed under ES5 strict mode.

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

1 Comment

I think the intention is to add objects to, say, data[0].children.push({label:'child3'}). But I may be wrong about that. ;-)

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.