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

asked Jun 18, 2013 at 15:03
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

answered Jun 18, 2013 at 15:11
6
  • i want to make it json object, how? Commented Jun 18, 2013 at 15:13
  • 1
    +1 for the correct answer. Sadly, I don't think it's going to help. Commented Jun 18, 2013 at 15:14
  • JSON stands for Javascript Object Notation meaning you are writing plain Javascript. JSON === javascript object Commented Jun 18, 2013 at 15:15
  • @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. Commented Jun 18, 2013 at 15:19
  • @abualbara It's an object, just like what you have. Commented Jun 18, 2013 at 15:19
1

You need:

var newShape="shape2";
JSONObject[newShape].id = "blar"; 
answered Jun 18, 2013 at 15:06
1
  • then, i can use that: JSONObject.shape2.id ? Commented Jun 18, 2013 at 15:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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