Javascript object property with variable name [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 never thought I'd stumble in a problem like that but hey what do you know..
var prop = 'horses'
console.log({
prop: 1
});
How can I have this produce an object with a property horses instead of prop and possibly have it done in a single line? Because I can think of a solution but what I'm really looking for is a one-liner.

You can use bracketed notation:
var obj = {};
obj[prop] = 1;
console.log(obj);
In JavaScript, you can refer to a property either by dot notation and a literal name (foo.bar), or bracketed notation with a string name (foo["bar"]). In the latter case, the string can be the result of any expression, including (in your case) a variable reference.
...but what I'm really looking for is a one-liner.
There's no way to do that as part of an object initializer, though, you have to do it separately. If you want a one-liner, you'll need to do a function call, e.g.:
console.log(makeObj(prop, 1));
where makeObj is
function makeObj(propName, propValue) {
var obj = {};
obj[propName] = propValue;
return obj;
}

Try using JSON to create the object:
console.log(JSON.parse("{\"" + prop + "\":\"1\"}");

Related

What's the difference between two ways of adding property to an existing js object? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
Let's say we need to add a property to an existing js object
var billingData = {}
In my case, I want to store input value in the js object
Here's the basic input
<input type="text" class="form-control" id="billingFullName">
We, basically, have two ways to add the property to the js object:
The first one:
billingData["billingFullName"] = document.getElementById('billingFullName').value
And the second one:
billingData.billingFullName = document.getElementById('billingFullName').value
What's the difference between them?
I'm asking, because when I was submitting the js object using AJAX to MVC Controller, where properties where added using the [] notation, the model in the Controller appeared to be null. Whereas, the dot notation appeared to solve the issue and I'm wondering why..
Typically you use bracket notation when you need to define a property dynamically such as with a variable or if the key is not in proper format for dot notation:
const obj = {}
const someKey = 'key'
obj[someKey] = 'somevalue'
console.log(obj.key) // 'somevalue'
console.log(obj.someKey) // undefined
Dot notation is when you already know the key:
const obj = {}
object.key = 'someValue'

Is it an object or array? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
I cannot understand the following code, var formData = {}; I guess defines a object "formData", but why to save each element in the formdata["fullName"]? What is this with []? Isn't it used for array? i confused. Could somebody explain this code? Thank you!
function readFormData(){
var formData = {};
formdata["fullName"] = document.getElementById("fullName").value;
formdata["empID"] = document.getElementById("empID").value;
formdata["salary"] = document.getElementById("salary").value;
formdata["city"] = document.getElementById("city").value;
return formData;
}
In javascript, array keys are defined and referenced with square brackets. Object properties can be defined an accessed the same way or with dot notation.
In your case you do have an object, and it's properties can be accessed using bracket notation.
The following two lines are thus equal:
obj["property"] = value;
obj.property = value;

How to convert string stored in variable of javascript directly to object property? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 4 years ago.
var str="firstname";
var obj={};
obj.str="john";
I want to create property firstname but i want to create it by the variable name like obj.str not like obj.firstname here problem is obj.str create property str not firstname.
i want to create property like this because it will later help me to create property by joining two string .
Try like this with [] notation.
See MDN when to use dot(.) or bracket([]) notation for javascript.
var str = "firstname";
var obj = {};
obj[str] = "john";
console.log(obj);

Is there a way to name a property by string on object creation? [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.
Is it possible to name a object property directly inside the object declaration itself, insted of doing it afterwards?
For examle, this works:
var name = "foo";
var obj = {};
obj[name] = "bar; // obj.foo === "bar"
But is there a way to do it somehow inside the object itself, like:
var name = "foo";
var obj = {
name: "bar" // obj.name === "bar"
};
I know it is possible to use strings for property names, so I was thinking something like this should do as workaround, but it didn't:
var obj = {
"" + name: "bar"
};
Is there a way to do this?
There is in ES2015, otherwise in ES5, there is no way to do that
var name = "foo";
var obj = {
[name]: "bar"
};
console.log(obj)
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed as the property name. This is
symmetrical to the bracket notation of the property accessor syntax,
which you might have used to read and set properties already. Now you
can use the same syntax in object literals, too.
Computed properties in object initializers on MDN

How to use the value of a variable in creating an object in JavaScript [duplicate]

This question already has answers here:
How to create an object property from a variable value in JavaScript? [duplicate]
(9 answers)
Closed 9 years ago.
I have an object:
var obj = {fields : []};
And a variable:
var x = "property_name";
Now how do I use the value in the variable x as the property name for the object that I'm going to push inside the array?
I tried something like the one below, but it takes x literally and uses it as the property name. What I want to use is the value stored in the variable x. Is that possible?
obj.fields.push({x : 'im a value'});
You cannot use the object literal syntax for this purpose. However, you can create a new object and then use the [] syntax - remember, obj.xyz is equivalent to obj['xyz'] - but as you can see with the quotes in the latter, you can use an expression there - such as a variable:
var x = "property_name";
var obj = {};
obj[x] = 'value';
obj.fields.push(obj);

Categories

Resources