zzy
zzy

Reputation: 1793

Create nested Json in js

I want to create Json like this:

{
    "name":"name",
    "children":[
        {
            "childName":"name"
        },
        {
            "childName":"name"
        }
    ]
}

I don't know how to place none-named property in json obj and place and obj into "children".

Upvotes: 0

Views: 170

Answers (2)

Faiz Shukri
Faiz Shukri

Reputation: 95

If you ask how to manipulate that JSON object, then maybe this would help.

Your original object:

var object = {
        "name":"name",
        "children":[
            {
                "childName":"name"
            },
            {
                "childName":"name"
            }
        ]
    };

1) How to place none-named property in json obj.

Object is not array, so should assign key/value, though either or both of them were empty. You can insert using dot or like array assignment.

object.country = "Malaysia";
object[""] = "No Keys";
object["novalue"] = "";

2) How to place an obj into "children".

var aNewChild = {
    "childName": "Handsome one"
};

object.children.push(aNewChild);

Upvotes: 0

LNT
LNT

Reputation: 916

OK, if you mean key itself is variable then you cannot create json-object in single shot, you will have to create it using '[]' notation

var myObj = {}; 
myObj[myProp1] = [] //or some value or some json/map again
myObj[myProp2] = 'hi'

myProp1 and myProp2 are variables.if you can explain your problem in more detail then you will get more clear answer.

Upvotes: 2

Related Questions