I'm looking to add an array of values to an array in an object but for some reason, the structure doesn't look right.
I start with the empty object:
var title = "name";
var kw = "fashion";
objectName = {[title]: [] };
I then push a string into the array:
objectName[title].push(kw);
However, when I console.log objectName, I get the following screenshot:
I would like to have the following structure instead:
{"name":["Item 1", "Item 2", "Item 3", "Item 4"]}
Am I building the array incorrectly? I'm just confused as to why the property name (utm_term [assisting]) appears under the array as well.
1 Answer 1
If the property is supposed to be called name (the value of title), then your code would be fine in ES2015+ (the new JavaScript standard from June), but you're probably using it in ES5 or earlier as that's what most JavaScript engines currently support.
In that case, you need to break your objectName initialization into two parts:
objectName = {};
objectName[title] = [];
E.g.:
var title = "name";
var kw = "fashion";
var objectName = {};
objectName[title] = [];
objectName[title].push(kw);
snippet.log(JSON.stringify(objectName, null, 2)); // Just using JSON for output display
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
(I assume you've declared the objectName variable somewhere. If not, be sure to add the var I added above, otherwise you fall prey to The Horror of Implicit Globals.)
titleorname(orutm_term, orassisting)?