declaring object using variable [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 3 years ago.
I am trying to use a variable when declaring an object:
var name1 = "object1";
var data1 = 3;
create_object(name1, data1);
function create_object(name, data) {
var x = {
name: data
}
return x
}
I want x to be stored as
var x = {
object1: 3
}
But my function will make
var x = {
name: 3
}
Is there a way to pass a variable when declaring the name of a child inside an object?
Thanks a lot

To specify a name of a property from a variable you need to use the square brackets notation like this:
function create_object(name, data) {
var x = {};
x[name] = data;
return x;
}

Related

Unable to bind javascript variable to JSON object key [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 4 months ago.
I am trying to add a value in place of json object key but it always returns variable name.
My Code:
var projectName='';
let tempArray=[];
let output={};
for(i=0;i<myJsonArray.length;i++){
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output= {projectName :tempArray};
console.log(JSON.stringify(output));
This returns a JSON as
{"projectName":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
But I need something like this:
{"ABC":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
Can someone help on what I am missing here.
Kind Regards.
You should wrap the project name into [] that would help to make a value become a key
var name = '';
let tempArray = [];
let output = {};
for (i = 0; i < myJsonArray.length; i++) {
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output = {
[name]: tempArray
};
console.log(JSON.stringify(output));
P/s: I don't see any projectName variable there, so I replace it by name instead.

How to log both variable and its name? [duplicate]

This question already has answers here:
How to console log the name of a variable/function?
(6 answers)
Closed 3 years ago.
I find myself typing this repeatedly for debugging in my code. Is there a way to create a function for this?
var abc = 1
console.log("abc = "+abc);
var xyz = 2;
console.log("xyz = "+xyz);
I would like to create a function like this:
logVar = function(input){
console.log(input.name()+" = "+input);
}
Is there a way to do this?
logVar(abc) should return "abc = 1"
logVar(xyz) should return "xyz = 2"
You have to enclose you var in a object to get its name as a key:
var myVar = 'John Doe';
console.log({myVar}); // result {"myVar": "John Doe"}
You can create an object from your variable which you pass into logVar.Then, in your function, you can use Object.entires to get the name of the variable and the value of the variable.
See example below:
var logVar = function (input) {
var [[name, val]] = Object.entries(input);
console.log(name, "=", val);
}
var abc = 1;
var xyz = 2;
logVar({abc}); // abc = 1
logVar({xyz}); // xyz = 2
Though this is not a proper solution, you can loop over the window object, but you can get other identifiers as well which hold the same value as the passed in argument. This only works in global scope & not while in function scope.
var ident = "wowowowow";
console.log(getIdentifierName(ident));
function getIdentifierName(identifier) {
for (var prop in window) {
if (window[prop] === identifier) {
console.log(identifier);
}
}
}
This should work:
var abc = 1;
logVar = function(input) {
console.log(input);
}
logVar({
abc
});
The output should be something like : { abc: 1 }

use variable on left side of object declaration [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
Is there any option as I can use a variable on the left side of my object declaration? Something like this:
var col = 'col';
var gridDataVK4000 = {
items : []
};
for (var i = 0; i <= 14; i++) {
col += col + i;
// we now push to the item property
gridDataVK4000.items.push({
col : i,
});
}
because my example isn't working. :(
You'll need to declare it outside of the curly braces using square bracket notation, otherwise you're assigning the key "col", literally, to your object.
var result = {};
result[col] = i;
gridDataVK4000.items.push(result);

Assign variable content to object property name [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 6 years ago.
I want to create a json object in node.js that looks like this;
{ WantThisName: { property_length: 8 } }
Here is my code;
var property_name = "WantThisName"
var length = 8;
var Obj_bin;
Obj_bin= {property_name: {property_length:length} };
console.log (Obj_bin);
The console output is;
{ property_name: { property_length: 8 } }
The problem lies with property_name not getting the contents of the variable property_name.
You can use computed (dynamic) property names:
> foo = "foozz"
'foozz'
> {[foo]: 42}
{ foozz: 42 }
They're part of the Enhanced Object Literals of es2015 (https://github.com/lukehoban/es6features#enhanced-object-literals).
For your example:
> var property_name = "WantThisName";
var property_name = "WantThisName";
undefined
> var length = 8;
undefined
> {[property_name]: { property_length: length}}
{ WantThisName: { property_length: 8 } }
>
try
Obj_bin = {};
Obj_bin[property_name] = { property_length: 8 };

How to dynamically generate variables in JavaScript? [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Use variable for property name in JavaScript literal?
(3 answers)
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 8 years ago.
My goal is to dynamically generate variables foo1, foo2 and foo3 and assign bar to them using the following code:
for (var i=1;i<=3;i++) {
myapp.set({ foo+i: "bar" })
}
I tried using eval on foo by it doesn't work. Any ideas?
for (var i=1;i<=3;i++) {
var myObj = {};
myObj['foo' + i] = 'bar';
myapp.set(myObj);
}
You can do this with square brackets. If you want the variables to be in the global scope, then use window['foo'+i].
Eg:
for (var i=1; i<=3; i++) {
window['foo'+i] = 'bar';
// OR, if you want them in 'myApp' scope:
myApp['foo'+i] = 'bar';
}
http://jsfiddle.net/TASfG/
var myApp = {};
for (var i=1; i <= 3; i++) {
myApp['foo'+i] = "bar";
}
console.log(myApp);

Categories

Resources