1

I'm not sure I'm asking this exactly right, but here's the situation.

I have an existing JSON object like this and I need to "inject" a new object into this where indicated:

{
 "version": "1.0.0",
 "stat_tag": "API",
 "layers": [{
 "type": "cartodb",
 "options": {
 "sql": "SELECT * FROM mytable)",
 "cartocss": "mytable{marker-width: 10;}",
 "cartocss_version": "2.1.0"
 }
 }
 //INSERT NEW OBJECT HERE
 ]
}

The object I need to inject is stored as a variable, I just don't know how to push it into the existing object in the right place.

Tushar
87.3k21 gold badges164 silver badges182 bronze badges
asked Jun 11, 2015 at 12:38

1 Answer 1

6

Push it into layers:

myObj.layers.push(newEl);

As the layers is an array push will add the newEl at the end of it.

var myObj = {
 "version": "1.0.0",
 "stat_tag": "API",
 "layers": [{
 "type": "cartodb",
 "options": {
 "sql": "SELECT * FROM mytable)",
 "cartocss": "mytable{marker-width: 10;}",
 "cartocss_version": "2.1.0"
 }
 }
 //INSERT NEW OBJECT HERE
 ]
};
var newEl = {
 "name": "Tushar"
}; // Object to add
myObj.layers.push(newEl);
console.log(myObj);
answered Jun 11, 2015 at 12:39
4
  • Okay, so in this script, what is myObj and what is newEl? Commented Jun 11, 2015 at 12:42
  • 1
    @jonmrich When there is no key layers on which you are pushing newEl Commented Jun 11, 2015 at 12:54
  • I think I see the problem. I over-simplified my example a bit, so your solution is right for the example, but not what I actually have. I really need to push the new object into something like this: layers: Array[1]0: Objectoptions: Objectsub: SubLayertype: "cartodb"__proto__: Objectlength: 1__proto__: Array[0] So, basically, I need to push object 1 into this layers object. How do I do that? Commented Jun 11, 2015 at 13:03
  • I keep trying to push in the new data and console.log the entire object, but my console just returns "2" Commented Jun 11, 2015 at 13:07

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.