How to create an object property from a variable value in JavaScript?
There's the dot notation and the bracket notation
myObj[a] = b;
JavaScript set object key by variable
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
How To Set A JS object property name from a variable
var jsonVariable = {};
for(var i=1; i < 3; i++) {
jsonVariable[i + 'name'] = 'name' + i;
}
Create object property from variable contents
You can't assign a dynamic property name like that, but you can use the []
notation:
var myobj = {};
myobj[$(this).attr('id')] = value;
- MDN Working with objects is a good resource covering this method.
Using Variable for Property Name of Object - Javascript
To set variables as key names you have to use bracket notation;
console.log(first); // returns 'name'
var obj = {};
obj[first] = value;
objArr[key] = obj; // no longer a problem
Sorry it's more verbose :(
Edit;
In ES6 you can now use computed-property-names;
const key = 'name';
const value = 'james';
const obj = {
[key]: value
};
create object using variables for property name
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.
Add a property to a JavaScript object using a variable as the name?
You can use this equivalent syntax:
obj[name] = value
Example:
let obj = {};
obj["the_key"] = "the_value";
or with ES6 features:
let key = "the_key";
let obj = {
[key]: "the_value",
};
in both examples, console.log(obj)
will return: { the_key: 'the_value' }
Create a Variable with an Object Property - Angular
- You are redefining
res
in your passed in function tomap
. - Use a plural of
name
tonames
, you want a string array so the plural is more appropriate and conveys what the field contains. - Do not try to access a non existent field or index on
res
, you hadres['']
which is not correct. - I put the call in
ngOnInit
, it might be located elsewhere but this allowed me to define the assigned variable member above it.
names: string[];
ngOnInit() {
this.mainService.getGraph()
.subscribe(res => {
console.log(res);
this.names = res.map(_ => _.name);
console.log(this.names);
}
From the comments:
...the IDE says property 'map' doesnt exist on type 'Object'. would it just be a bug
About your service. Make sure the signature is correct on the return type. Here is an example, you can also define an interface and return that instead of {name:string}
(but keep the [] which denotes there is an array being returned).
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export class MainService {
constructor(private readonly http: HttpClient){}
getGraph() : Observable<{name: string}[]> {
return this.http.get<{name: string}[]>('/some/url');
}
}
Related Topics
Insert HTML into View from Angularjs Controller
How to Deep Merge Instead of Shallow Merge
Calling Functions With Settimeout()
How to Enumerate the Properties of a JavaScript Object
Updating a Nested Array With Mongodb
How to Test For an Empty JavaScript Object
How to Insert an Item into an Array At a Specific Index (JavaScript)
Group Array Items Using Object
Remove Accents/Diacritics in a String in JavaScript
How to Access the Matched Groups in a JavaScript Regular Expression
Web-Scraping JavaScript Page With Python
Uncaught Referenceerror: $ Is Not Defined
How to Create a File in Memory For User to Download, But Not Through Server