1

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";

NOTE: The first thing, is that a json object? Any help will be appreciated

11
  • this uses arrays not json object, isn't it? Commented Jun 18, 2013 at 15:06
  • Java has nothing to do with Javascript. Tag removed. Commented Jun 18, 2013 at 15:08
  • 1
    What you are doing makes no sense. Commented Jun 18, 2013 at 15:09
  • This is not a JSON object. It's a JavaScript object. Commented Jun 18, 2013 at 15:09
  • @Joe : could you plz give me the right JSON object Commented Jun 18, 2013 at 15:12

2 Answers 2

4

Assuming you want to build a similar structure as the rest:

JSONObject.shape2 = {
    id: 'id2',
    "x1": 4,
    "x2": 4,
    "y1": 4,
    "y2": 8
};

Or:

var shapeName = 'shape2';
JSONObject[shapeName] = {
    ...
};

Btw, these are not JSON objects; they are just objects, in JavaScript.

Update

The following wouldn't work:

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

First of all, the notation is wrong; you need to use [newShape]. But that's not the main reason; it doesn't work because you can't dereference an object that doesn't exist yet.

JSONObject[newShape]

This will be undefined, so this:

JSONObject[newShape].id

Will result in an error TypeError: Cannot set property 'id' of undefined

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

6 Comments

i want to make it json object, how?
+1 for the correct answer. Sadly, I don't think it's going to help.
JSON stands for Javascript Object Notation meaning you are writing plain Javascript. JSON === javascript object
@Pinoniq Not sure if you're agreeing with me or not; but yeah, JSON is just a notation; it's not plain JavaScript though, because keys must be quoted in JSON.
@abualbara It's an object, just like what you have.
|
1

You need:

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

1 Comment

then, i can use that: JSONObject.shape2.id ?

Your Answer

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