How to convert string as object's field name in javascript - javascript

I have a js object like:
obj = {
name: 'js',
age: 20
};
now i want to access name field of obj, but i can only get string 'name', so how to convert 'name' to obj's field name, then to get result like obj.name.
Thank you in advance.

You can access the properties of javascript object using the index i.e.
var obj = {
name: 'js',
age: 20
};
var isSame = (obj["name"] == obj.name)
alert(isSame);
var nameIndex = "name"; // Now you can use nameIndex as an indexor of obj to get the value of property name.
isSame = (obj[nameIndex] == obj.name)
Check example# : http://www.jsfiddle.net/W8EAr/

In Javascript, obj.name is equivalent to obj['name'], which adds the necessary indirection.
In your example:
var fieldName = 'name'
var obj = {
name: 'js',
age: 20
};
var value = obj[fieldName]; // 'js'

Not related at all, but for anyone trying to define object's field name from a string variable, you could try with:
const field = 'asdf'
const obj = {[field]: 123}
document.body.innerHTML = obj.asdf

It's quite simple, to access an object's value via a variable, you use square brackets:
var property = 'name';
var obj = {name: 'js'};
alert(obj[property]); // pops 'js'

As objects are associative arrays in javascript you can access the 'name' field as obj['name'] or obj[fieldName] where fieldName = 'name'.

Related

Use variable as property JavaScript [duplicate]

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
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,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
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 and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;

javascript map(val , index) , which condition val is variable and string [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 months ago.
I'm pulling items out of the DOM with jQuery and want to set a property on an object using the id of the DOM element.
Example
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// Here is the problem
obj.name = value
})
If itemsFromDom includes an element with an id of "myId", I want obj to have a property named "myId". The above gives me name.
How do I name a property of an object using a variable using JavaScript?
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' }
With ECMAScript 2015 you can do it directly in object declaration using bracket notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value:
var obj = {
['hello']: 'World',
[x + 2]: 42,
[someObject.getId()]: someVar
}
You can even make List of objects like this
var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
var feeType = {};
var $ID = $(this).find("input[id^=txtFeeType]").attr('id');
feeType["feeTypeID"] = $('#ddlTerm').val();
feeType["feeTypeName"] = $('#ddlProgram').val();
feeType["feeTypeDescription"] = $('#ddlBatch').val();
feeTypeList.push(feeType);
});
There are two different notations to access object properties
Dot notation: myObj.prop1
Bracket notation: myObj["prop1"]
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
So, these all set the myObj property named prop1 to the value Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
With lodash, you can create new object like this _.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
First we need to define key as variable and then we need to assign as key as object., for example
var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)
Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:
this.setState({ [`${name}`]: value}, () => {
console.log("State updated: ", JSON.stringify(this.state[name]));
});
PS: Please mind the quote character.
With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:
var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
ajavascript have two type of annotation for fetching javascript Object properties:
Obj = {};
1) (.) annotation eg. Obj.id
this will only work if the object already have a property with name 'id'
2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.
so for below example:
A new property will be created always when you write Obj[name].
And if the property already exist with the same name it will override it.
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// This will work
obj[name]= value;
})
If you want to add fields to an object dynamically, simplest way to do it is as follows:
let params = [
{ key: "k1", value: 1 },
{ key: "k2", value: 2 },
{ key: "k3", value: 3 },
];
let data = {};
for (let i = 0; i < params.length; i++) {
data[params[i].key] = params[i].value;
}
console.log(data); // -> { k1: 1, k2: 2, k3: 3 }
The 3 ways to access the object value
We can output the object value by passing in the appropriate key. Because I used emoji as the key in my example, it's a bit tricky. So let's look at a easier example.
let me = {
name: 'samantha',
};
// 1. Dot notation
me.name; // samantha
// 2. Bracket notation (string key)
me['name']; // samantha
// 3. Bracket notation (variable key)
let key = 'name';
me[key]; // samantha
know more
If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.
Object.keys(myObject)
.map(el =>{
const obj = {};
obj[el]=myObject[el].code;
console.log(obj);
});
objectname.newProperty = value;
const data = [{
name: 'BMW',
value: '25641'
}, {
name: 'Apple',
value: '45876'
},
{
name: 'Benz',
value: '65784'
},
{
name: 'Toyota',
value: '254'
}
]
const obj = {
carsList: [{
name: 'Ford',
value: '47563'
}, {
name: 'Toyota',
value: '254'
}],
pastriesList: [],
fruitsList: [{
name: 'Apple',
value: '45876'
}, {
name: 'Pineapple',
value: '84523'
}]
}
let keys = Object.keys(obj);
result = {};
for(key of keys){
let a = [...data,...obj[key]];
result[key] = a;
}

What does this bracket mean in typescript [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 months ago.
I'm pulling items out of the DOM with jQuery and want to set a property on an object using the id of the DOM element.
Example
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// Here is the problem
obj.name = value
})
If itemsFromDom includes an element with an id of "myId", I want obj to have a property named "myId". The above gives me name.
How do I name a property of an object using a variable using JavaScript?
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' }
With ECMAScript 2015 you can do it directly in object declaration using bracket notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value:
var obj = {
['hello']: 'World',
[x + 2]: 42,
[someObject.getId()]: someVar
}
You can even make List of objects like this
var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
var feeType = {};
var $ID = $(this).find("input[id^=txtFeeType]").attr('id');
feeType["feeTypeID"] = $('#ddlTerm').val();
feeType["feeTypeName"] = $('#ddlProgram').val();
feeType["feeTypeDescription"] = $('#ddlBatch').val();
feeTypeList.push(feeType);
});
There are two different notations to access object properties
Dot notation: myObj.prop1
Bracket notation: myObj["prop1"]
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
So, these all set the myObj property named prop1 to the value Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
With lodash, you can create new object like this _.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
First we need to define key as variable and then we need to assign as key as object., for example
var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)
Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:
this.setState({ [`${name}`]: value}, () => {
console.log("State updated: ", JSON.stringify(this.state[name]));
});
PS: Please mind the quote character.
With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:
var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
ajavascript have two type of annotation for fetching javascript Object properties:
Obj = {};
1) (.) annotation eg. Obj.id
this will only work if the object already have a property with name 'id'
2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.
so for below example:
A new property will be created always when you write Obj[name].
And if the property already exist with the same name it will override it.
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// This will work
obj[name]= value;
})
If you want to add fields to an object dynamically, simplest way to do it is as follows:
let params = [
{ key: "k1", value: 1 },
{ key: "k2", value: 2 },
{ key: "k3", value: 3 },
];
let data = {};
for (let i = 0; i < params.length; i++) {
data[params[i].key] = params[i].value;
}
console.log(data); // -> { k1: 1, k2: 2, k3: 3 }
The 3 ways to access the object value
We can output the object value by passing in the appropriate key. Because I used emoji as the key in my example, it's a bit tricky. So let's look at a easier example.
let me = {
name: 'samantha',
};
// 1. Dot notation
me.name; // samantha
// 2. Bracket notation (string key)
me['name']; // samantha
// 3. Bracket notation (variable key)
let key = 'name';
me[key]; // samantha
know more
If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.
Object.keys(myObject)
.map(el =>{
const obj = {};
obj[el]=myObject[el].code;
console.log(obj);
});
objectname.newProperty = value;
const data = [{
name: 'BMW',
value: '25641'
}, {
name: 'Apple',
value: '45876'
},
{
name: 'Benz',
value: '65784'
},
{
name: 'Toyota',
value: '254'
}
]
const obj = {
carsList: [{
name: 'Ford',
value: '47563'
}, {
name: 'Toyota',
value: '254'
}],
pastriesList: [],
fruitsList: [{
name: 'Apple',
value: '45876'
}, {
name: 'Pineapple',
value: '84523'
}]
}
let keys = Object.keys(obj);
result = {};
for(key of keys){
let a = [...data,...obj[key]];
result[key] = a;
}

JavaScript: Fetch Headers: Object literal does not add custom header, new Header() obj does [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 months ago.
I'm pulling items out of the DOM with jQuery and want to set a property on an object using the id of the DOM element.
Example
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// Here is the problem
obj.name = value
})
If itemsFromDom includes an element with an id of "myId", I want obj to have a property named "myId". The above gives me name.
How do I name a property of an object using a variable using JavaScript?
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' }
With ECMAScript 2015 you can do it directly in object declaration using bracket notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value:
var obj = {
['hello']: 'World',
[x + 2]: 42,
[someObject.getId()]: someVar
}
You can even make List of objects like this
var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
var feeType = {};
var $ID = $(this).find("input[id^=txtFeeType]").attr('id');
feeType["feeTypeID"] = $('#ddlTerm').val();
feeType["feeTypeName"] = $('#ddlProgram').val();
feeType["feeTypeDescription"] = $('#ddlBatch').val();
feeTypeList.push(feeType);
});
There are two different notations to access object properties
Dot notation: myObj.prop1
Bracket notation: myObj["prop1"]
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
So, these all set the myObj property named prop1 to the value Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
With lodash, you can create new object like this _.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
First we need to define key as variable and then we need to assign as key as object., for example
var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)
Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:
this.setState({ [`${name}`]: value}, () => {
console.log("State updated: ", JSON.stringify(this.state[name]));
});
PS: Please mind the quote character.
With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:
var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
ajavascript have two type of annotation for fetching javascript Object properties:
Obj = {};
1) (.) annotation eg. Obj.id
this will only work if the object already have a property with name 'id'
2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.
so for below example:
A new property will be created always when you write Obj[name].
And if the property already exist with the same name it will override it.
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// This will work
obj[name]= value;
})
If you want to add fields to an object dynamically, simplest way to do it is as follows:
let params = [
{ key: "k1", value: 1 },
{ key: "k2", value: 2 },
{ key: "k3", value: 3 },
];
let data = {};
for (let i = 0; i < params.length; i++) {
data[params[i].key] = params[i].value;
}
console.log(data); // -> { k1: 1, k2: 2, k3: 3 }
The 3 ways to access the object value
We can output the object value by passing in the appropriate key. Because I used emoji as the key in my example, it's a bit tricky. So let's look at a easier example.
let me = {
name: 'samantha',
};
// 1. Dot notation
me.name; // samantha
// 2. Bracket notation (string key)
me['name']; // samantha
// 3. Bracket notation (variable key)
let key = 'name';
me[key]; // samantha
know more
If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.
Object.keys(myObject)
.map(el =>{
const obj = {};
obj[el]=myObject[el].code;
console.log(obj);
});
objectname.newProperty = value;
const data = [{
name: 'BMW',
value: '25641'
}, {
name: 'Apple',
value: '45876'
},
{
name: 'Benz',
value: '65784'
},
{
name: 'Toyota',
value: '254'
}
]
const obj = {
carsList: [{
name: 'Ford',
value: '47563'
}, {
name: 'Toyota',
value: '254'
}],
pastriesList: [],
fruitsList: [{
name: 'Apple',
value: '45876'
}, {
name: 'Pineapple',
value: '84523'
}]
}
let keys = Object.keys(obj);
result = {};
for(key of keys){
let a = [...data,...obj[key]];
result[key] = a;
}

Add a property to a JavaScript object using a variable as the name? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 months ago.
I'm pulling items out of the DOM with jQuery and want to set a property on an object using the id of the DOM element.
Example
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// Here is the problem
obj.name = value
})
If itemsFromDom includes an element with an id of "myId", I want obj to have a property named "myId". The above gives me name.
How do I name a property of an object using a variable using JavaScript?
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' }
With ECMAScript 2015 you can do it directly in object declaration using bracket notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value:
var obj = {
['hello']: 'World',
[x + 2]: 42,
[someObject.getId()]: someVar
}
You can even make List of objects like this
var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
var feeType = {};
var $ID = $(this).find("input[id^=txtFeeType]").attr('id');
feeType["feeTypeID"] = $('#ddlTerm').val();
feeType["feeTypeName"] = $('#ddlProgram').val();
feeType["feeTypeDescription"] = $('#ddlBatch').val();
feeTypeList.push(feeType);
});
There are two different notations to access object properties
Dot notation: myObj.prop1
Bracket notation: myObj["prop1"]
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
So, these all set the myObj property named prop1 to the value Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
With lodash, you can create new object like this _.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
First we need to define key as variable and then we need to assign as key as object., for example
var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)
Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:
this.setState({ [`${name}`]: value}, () => {
console.log("State updated: ", JSON.stringify(this.state[name]));
});
PS: Please mind the quote character.
With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:
var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
ajavascript have two type of annotation for fetching javascript Object properties:
Obj = {};
1) (.) annotation eg. Obj.id
this will only work if the object already have a property with name 'id'
2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.
so for below example:
A new property will be created always when you write Obj[name].
And if the property already exist with the same name it will override it.
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// This will work
obj[name]= value;
})
If you want to add fields to an object dynamically, simplest way to do it is as follows:
let params = [
{ key: "k1", value: 1 },
{ key: "k2", value: 2 },
{ key: "k3", value: 3 },
];
let data = {};
for (let i = 0; i < params.length; i++) {
data[params[i].key] = params[i].value;
}
console.log(data); // -> { k1: 1, k2: 2, k3: 3 }
The 3 ways to access the object value
We can output the object value by passing in the appropriate key. Because I used emoji as the key in my example, it's a bit tricky. So let's look at a easier example.
let me = {
name: 'samantha',
};
// 1. Dot notation
me.name; // samantha
// 2. Bracket notation (string key)
me['name']; // samantha
// 3. Bracket notation (variable key)
let key = 'name';
me[key]; // samantha
know more
If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.
Object.keys(myObject)
.map(el =>{
const obj = {};
obj[el]=myObject[el].code;
console.log(obj);
});
objectname.newProperty = value;
const data = [{
name: 'BMW',
value: '25641'
}, {
name: 'Apple',
value: '45876'
},
{
name: 'Benz',
value: '65784'
},
{
name: 'Toyota',
value: '254'
}
]
const obj = {
carsList: [{
name: 'Ford',
value: '47563'
}, {
name: 'Toyota',
value: '254'
}],
pastriesList: [],
fruitsList: [{
name: 'Apple',
value: '45876'
}, {
name: 'Pineapple',
value: '84523'
}]
}
let keys = Object.keys(obj);
result = {};
for(key of keys){
let a = [...data,...obj[key]];
result[key] = a;
}

Categories

Resources