Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I saw many questions in Stackoverflow but i didn't find what exactly responds to my query.

I need to add an element to my json object:

var JSONObject = {
    "shape0": {
        "id": "id0",
        "x1": 0,
        "x2": 0,
        "y1": 0,
        "y2": 0
    },
    "shape1": {
        "id": "id1",
        "x1": 2,
        "x2": 2,
        "y1": 2,
        "y2": 2
    }
};

I used this syntax but in vain:

var newShape = "shape2";
JSONObject.newShape.id = "id2";

Any help will be appreciated

share
1  
this uses arrays not json object, isn't it? – abu albara 3 mins ago
Java has nothing to do with Javascript. Tag removed. – Brian Roach 58 secs ago
The selected answer does I suppose, the second answer uses jquery's extend. You did tag jquery. – smerny 53 secs ago
What you are doing makes no sense. – daveL 20 secs ago
show 1 more comment

2 Answers

You need:

var newShape="shape2";
JSONObject[newShape].id = "blar"; 
share
then, i can use that: JSONObject.shape2.id ? – abu albara 59 secs ago

When using the literal property reference in a variable you need to use array notation. Try this:

var newShape = "shape2";
JSONObject[newShape].id = "id2";

The alternative in object notation would be this:

JSONObject.shape2.id = "id2";
share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.