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.
I have two variable, attribute (e.g. "type") and value (e.g. "car"). I want to make an object where the key is the attribute (and the value is the value). Like this: {"type": "car"}.
When I do
let obj = { attribute: value }
I get
> {"attribute": "car"}
This is easy with two lines, as I can just
let obj = {};
obj[attribute] = value;
However, I'm wondering if there is a clean way of doing this in one line (since I'm a former Rubyist and I like making things clean and precise)?
Computed property names, starting from ES2015 aka ES6.
let a = "type", b = "car";
console.log({[a]: b});
Related
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 5 years ago.
I have this snippet of code:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
arrLiteData.push({ii:{"field1":100,"field2":ii}});
}
...but instead of ii taking the increasing numeric value of ii, the array just holds the actual variable name, like this:
[{"ii":{"field1":100,"field2":0}},{"ii":{"field1":100,"field2":1}}...etc, etc...
What am I doing wrong?
Many thanks.
Quotes are optional for javascript object keys, so
{ii:{"field1":100,"field2":ii}} is the same as
{"ii":{"field1":100,"field2":ii}} or even
{ii:{field1:100,field2:ii}}. They are just need if you have non alphanumeric characters.
To solve this you could either use a computed key if you're transpiling your code or targeting recent navigators:
{[ii]:{"field1":100,"field2":ii}}
Or build the object in two steps:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
var obj = {};
obj[ii] = {"field1":100,"field2":ii};
arrLiteData.push(obj);
}
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Javascript: Get deep value from object by passing path to it as string [duplicate]
(5 answers)
Closed 5 years ago.
Consider I've an object myObj
And I've a string representing the path to some property inside it: foo.bar
What is the best way to get it from my object?
If I knew the string ahead I would do myObj.foo && myObj.foo.bar to get it safely
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
But i'm sure there is a better way
It's a duplicate of other question. they provided a great solution:
given a path and an obj get the property value this way
path.split('.').reduce((o, i) => o[i], obj)
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
Yep, that sounds like the best way. You can create a helper method that does exactly this, but there's nothing built in to the language or standard libraries to make things simpler than this.
function getFromPath(obj, path) {
var current = obj;
for(let piece of path.split('.')) {
current = current[piece];
}
return current;
}
Usage:
getFromPath({foo: {bar: "hello"}}, "foo.bar"); // "hello"
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 6 years ago.
I want to be able to take JSON into my program and then create objects based off of that data. So, I want to create objects where the name of that object is the value stored in a key value pair. For instance, if I had the following JSON (and I know this isn't perfect JSON):
{
"objectName" : "**variableName**",
"someDataName" : "thatData",
"someOtherDataName" : "thisData"
}
Then I want to be able to make an object like this:
function myObject(thatData, thisData) {
this.name = name;
this.thatData = thatData;
}
var **variableName** = new myObject(thatData, thisData);
The key here is that I want to be able to use the value stored in the ObjectName key value pair as the variable name for the object. Is this even possible? I have been looking for how to do this for a while now. I believe that this is different than "Variable" variables in Javascript? because I am trying to use a value in a key value pair to name my objects.
If I understand correctly what you're trying to do here, one approach may be to set properties within a variable:
let myContainer = {};
// ...
myContainer['whatever_variable_name'] = new ...
You can how use myContainer.whatever_variable_name or myContainer['whatever_variable_name'] to access the new object.
To assign properties from JSON objects, see Object.assign.
You can use the property accessor on the window object to set the value for a dynamic key on the global scope.
var window["**variableName**"] = new myObject(thatData, thisData);
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.
The way I usually do that,
var update = {};
update[name] = data;
update.resolved = true;
where, name is a variable.
I assume that's not the most efficient way of initialization, but it's not possible to use a variable in object notation initialization.
Other possible ways?
You can use computed property names (which is an ES6 feature, but given you tagged your question as such I assume that's not a problem):
var update = {
[name] : data,
resolved : true,
};
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 9 years ago.
I can't figure out how to use the name of a variable previously created with eval, without knowing it.
I mean:
function getName(menu_name, level){
eval("var menu_"+level+"="+menu_name);
}
Now how do I get the name of the variable I just created? Probably keep using eval, but I have to put that name into a $.post call as one of my field name.
Thanks in advice.
If level is an integer, you can treat it as a numerical index for an array:
var menu = [];
menu[level] = menu_name;
If level is anything else, you can treat it as a key for a dictionary/associative array:
var menu = {};
menu[level] = menu_name;
Then, for either of the solutions, if you want to access your menu_name, simply call menu[level].