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
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
-
Okay, so in this script, what is
myObj
and what isnewEl
?jonmrich– jonmrich06/11/2015 12:42:52Commented Jun 11, 2015 at 12:42 -
1@jonmrich When there is no key
layers
on which you are pushingnewEl
Tushar– Tushar06/11/2015 12:54:04Commented 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?jonmrich– jonmrich06/11/2015 13:03:06Commented 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"jonmrich– jonmrich06/11/2015 13:07:05Commented Jun 11, 2015 at 13:07
lang-js