How to add an object in an array? [duplicate] - javascript
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
I am trying to push object into an array
I have something like these
for(var i=0; i<test.length; i++){
console.log(test[i])
console.log(items[test[i]])
productObj.push( { test[i] : items[test[i]]} );
}
both console.log show stuff but I have an error on the push(). The error is "Uncaught SyntaxError: Unexpected token ["
Can anyone help me about this weird issue? Thanks!
Object literal keys need to be constant. test[i] isn't going to work. You'll need to create an empty object and add the key/value pair:
var o = {};
o[ test[i] ] = items[test[i]];
productObj.push( o );
The keys in an object literal are not evaluated and must be valid identifiers.
You would get the same error just from the object literal: { test[i]: 1 }.
You can use the new keyword in conjunction with an anonymous function to create the object instead:
productObj.push( new function () { this[test[i]] = items[test[i]]; } );
If you find that the above is less readable, then you should create the object in advance:
var temp = {};
temp[test[i]] = items[test[i]];
productObj.push( temp );
The key of an entry in the {} syntax for creating objects is not looked up as a variable, it must be a valid identifier. test[i] is not a valid identifier due to the brackets, and even if it was it would not get evaluated.
To create a key from test[i], you have to manually add it using the [] syntax.
var v = {};
v[test[i]] = ...
Related
JavaScript and Consts [duplicate]
This question already has answers here: How to use a variable for a key in a JavaScript object literal? (16 answers) Closed 4 months ago. const A = 0; const LOOKUP = { A : "A"}; console.log(LOOKUP[A]); console.log(LOOKUP[0]); Result: undefined undefined Second try: var A = 0; const LOOKUP = { A : "A"}; console.log(LOOKUP[A]); console.log(LOOKUP[0]); Result: undefined undefined How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?
The correct way is: const A = 0; const LOOKUP = {}; LOOKUP[A] = 'A'; console.log(LOOKUP[A]); console.log(LOOKUP[0]);
const LOOKUP = { A : "A"}; The left side of the colon means that the key is the string "A". The string part is implicit, since all keys are strings (or symbols). So to access the property, you need to do console.log(LOOKUP.A) or console.log(LOOKUP["A"]) If you want the key to be a computed value, then you need to use square brackets: const LOOKUP = { [A]: "A" }; That means that we should resolve the variable A, and use its value as the key. That key is the number 0, which then gets coerced into the string "0". You can then look it up by any of console.log(LOOKUP["0"]), console.log(LOOKUP[0]), or console.log(LOOKUP[A])
Looks like you are searching for some enums (typescript): enum ETest { A = 1 }; console.log(ETest['A']); // 1 console.log(ETest[1]); // A
Doing LOOKUP[A] is like doing LOOKUP[0] which is undefined. You should try it as console.log(LOOKUP["A"])
This has nothing to do with const or var keyword. The way you are trying to access an object property is incorrect. const A = 0; const LOOKUP = { A : "A"}; console.log(LOOKUP["A"]); // Correct Approach: Property access through bracket notation should be done using a string (or a variable assigned to a string). console.log(LOOKUP[0]); // Property `0` doesn't exist on object `LOOKUP`, so it'll return `undefined`.
Defining an object with a dynamic key in node js (javascript) [duplicate]
This question already has answers here: How To Set A JS object property name from a variable (8 answers) Closed 4 years ago. I need to do this : let obj = {} obj.obj1 = {'obj11':5} console.log(obj.obj1.obj11) //5 but I need to define the last key of the last object dynamically for example, something like this: let obj = {} key = 'obj11' obj.obj1 = { key :5} console.log(obj.obj1.obj11) // undefined
Try obj.obj1[key] = 5; console.log(obj.obj1.obj11); The object notation syntax does not support variables as keys directly, but java-script dictionaries do. To evaluate the variable in the object notation syntax, use a bracket like so obj.obj1 = {[key]: 5}; console.log(obj.obj1.obj11);
To define computed properties in javascript objects use []. Try the following: let obj = {} key = 'obj11' obj.obj1 = { [key] :5} console.log(obj.obj1.obj11) For reference : Reference
You'll have to use bracket notation for this like let obj = {} key = 'obj11' obj.obj1 = { [key] :5} console.log(obj.obj1.obj11)
Yes, you can do this: console.log(obj.obj1[key]); Every object in JavaScript is basically a dictionary so you can access it via the dictionary syntax.
Going through a object with a variable [duplicate]
This question already has answers here: JavaScript object: access variable property by name as string [duplicate] (3 answers) Closed 6 years ago. I guess I didnt really know how to ask this question for me to find an answer. So I have three variables that are going to make this function do what it has to function gatherDataForGeographic(ele) { var $this = $(ele) var $main_title = $this.find('.options-title'), $option = $this.find('.option'); var arr = [] var reportAreas = reportManager.getReportAreasObject(); $option.each(function () { var $this = $(this) var $checkbox = $this.find('.checkbox'); var type = $this.data('type'), index = $this.data('index'); if ($checkbox.hasClass('checkbox--checked')) { console.log(reportAreas.type) } else { return true; } }) return arr; } //this will return an object that I need to index var reportAreas = reportManager.getReportAreasObject(); //this will get the a key that i need from the object var type = $this.data('type'); //this will give me the index I need to grab var index = $this.data('index'); So what I am trying to do is go through the object based on the type(or key) from the option selected by a user The problem... It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist. Is there a way for it to see that type is a variable and not a key?
You can use dynamic properties in JS using the bracket syntax, not the dot syntax: reportAreas[type] That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.
reportArea[type][index] JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation. object['a'] and object.a Are the same thing, basically.
Jquery object assign to variable return undefined [duplicate]
This question already has answers here: Convert a JavaScript string in dot notation into an object reference (34 answers) Closed 7 years ago. Working SO code below: var property_object_parse = jQuery.parseJSON('{"p1":{"TextElement":[{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_company name","text":"Company name","font":"Plantagenet Cherokee","size":"9","h":"0.16","w":"1.15","y":"0.3","x":"0.53","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"company name","caption":"Company name","textType":"Company name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"left","sortorder":"0","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_first name","text":"First name","font":"Plantagenet Cherokee","size":"7","h":"0.1","w":"1.14","y":"0.44","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"first name","caption":"First name","textType":"First name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"1","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_last name","text":"Last Name","font":"Plantagenet Cherokee","size":"6","h":"0.11","w":"1.16","y":"0.56","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"last name","caption":"Last Name","textType":"Last Name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"2","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_email","text":"Email","font":"Plantagenet Cherokee","size":"6","h":"0.1","w":"1.14","y":"0.69","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"email","caption":"Email","textType":"Email","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"3","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_phone","text":"Phone","font":"Plantagenet Cherokee","size":"6","h":"0.11","w":"1.14","y":"0.81","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"phone","caption":"Phone","textType":"Phone","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"4","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_street","text":"street","font":"Plantagenet Cherokee","size":"9","h":"0.17","w":"1.16","y":"0.95","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"street","caption":"street","textType":"street","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"5","inputformat":false,"format":false,"clippath":false,"inputrequired":false}]},"p2":{"ImageElement":[{"type":"image","text":"Sample.png","blockName":"Back Logo","id":"#2_Back Logo","lock":"false","rotation":"0","h":"0.68","w":"0.69","y":"0.59","x":"0.41","valign":"bottom","halign":"left","clippath":false}],"TextElement":[{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#2_Company Name","text":"Company Name","font":"Plantagenet Cherokee","size":"9","h":"0.16","w":"1.16","y":"1.3","x":"0.24","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"Company Name","caption":"Company Name","textType":"Company Name","bold":"false","colorspace":"DevicaeRGB","colorcode":"rgb(1.00,0.00,0.00)","color":"16711680","hex_color":"","valign":"bottom","align":"center","sortorder":"0","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#2_Tagline","text":"Sample Tagline","font":"Helvetica","size":"12","h":"0.18","w":"0.73","y":"1.52","x":"0.25","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"Tagline","caption":"Sample Tagline","textType":"Sample Tagline","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"top","align":"left","sortorder":"1","inputformat":false,"format":false,"clippath":false,"inputrequired":false}]}}'); var selected_element = 'p1.TextElement[0].size'; console.log(property_object_parse.selected_element); I am getting undefined when I try to get the value using variable. Is this correct way to access it? See my jsfiddle here
property_object_parse is a real JavaScript object, so you can just use the member access syntax to access the value you are interested in directly: console.log(property_object_parse.p1.TextElement[0].size); Note that you cannot use a dynamic property path string like 'p1.TextElement[0].size', you would have to compile that in a way. For example, you could instead have an array of properties you are trying to access: var selected_element = ['p1', 'TextElement', '0', 'size']; var obj = property_object_parse; for (var i = 0; i < selected_element.length; i++) { obj = obj[selected_element[i]]; } console.log(obj); That has the same result as accessing it all directly as above with property_object_parse.p1.TextElement[0].size.
create object using variables for property name [duplicate]
This question already has answers here: How to use a variable for a key in a JavaScript object literal? (16 answers) Closed 7 years ago. Is it at all possible to use variable names in object literal properties for object creation? Example function createJSON (propertyName){ return { propertyName : "Value"}; } var myObject = createJSON("myProperty"); console.log(myObject.propertyName); // Prints "value" console.log(myObject.myProperty); // This property does not exist
If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets: var foo = "bar"; var ob = { [foo]: "something" }; // ob.bar === "something" If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel): Create the object first, and then add the property using square bracket notation. var foo = "bar"; var ob = {}; ob[foo] = "something"; // === ob.bar = "something" If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.
ES6 introduces computed property names, which allow you to do function CreateJSON (propertyName){ var myObject = { [propertyName] : "Value"}; } Note browser support is currently negligible.
You can sort of do this: var myObject = {}; CreateProp("myProperty","MyValue"); function CreateProp(propertyName, propertyValue) { myObject[propertyName] = propertyValue; alert(myObject[propertyName]); // prints "MyValue" }; I much perfer this syntax myself though: function jsonObject() { }; var myNoteObject = new jsonObject(); function SaveJsonObject() { myNoteObject.Control = new jsonObject(); myNoteObject.Control.Field1= "Fred"; myNoteObject.Control.Field2= "Wilma"; myNoteObject.Control.Field3= "Flintstone"; myNoteObject.Control.Id= "1234"; myNoteObject.Other= new jsonObject(); myNoteObject.Other.One="myone"; }; Then you can use the following: SaveJsonObject(); var myNoteJSON = JSON.stringify(myNoteObject); NOTE: This makes use of the json2.js from here:http://www.json.org/js.html
One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it. function func(prop, val) { var jsonStr = '{"'+prop+'":'+val+'}'; return JSON.parse(jsonStr); } var testa = func("init", 1); console.log(testa.init);//1 Just keep in mind, JSON property names need to be enclosed in double quotes.