Get object property using array of object name and proerty name - javascript

I want to find object property dynamically from array that map to property location.
Example
Var objectA = { a:{b:1} };
Var Names = ['objectA','a','b'];
Howa can i get value of b by looping over array Names ?

Assuming objectA is available in the global scope (window.objectA), you could do something like this:
names.reduce(function (memo, value) {
return memo[value];
}, window)
For any other "non-global" variable, you can create a getter function that takes the variable and the path (an array just like your names, but without the first value) as a parameter:
function nestedValue(obj, path) {
return path.reduce(function (memo, value) {
return memo[value];
}, obj);
}
BTW, please note that Array.prototype.reduce() is a ES2015 feature, so if you need to be compatible with older browsers, you would have to use some variation of for loop for this task.
You could also check out lodash.get for more sophisticated solution (if you're willing to include it in your project).

You can use eval: eval(Names.join('.'))
Can use this with nodejs inside a sandbox:
const util = require('util');
const vm = require('vm');
const objectA = { a: { b: 1 }};
const Names = ['objectA', 'a', 'b'];
const sandbox = { objectA: objectA, Names: Names };
vm.createContext(sandbox);
for (var i = 0; i < 10; ++i) {
vm.runInContext("var result = eval(Names.join('.'))", sandbox);
}
console.log(util.inspect(sandbox));
/* {
objectA: { a: { b: 1 } },
Names: [ 'objectA', 'a', 'b' ],
result: 1
}
*/

To do this without eval would require you store ObjectA as a property of another object that you could iterate over using the array keys. eval will work in this case though:
objectA = { a: { b: 1 }}
names = ['objectA', 'a', 'b']
alert(eval(names.join('.')))

Related

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;
}

Indexing a JSON by index instead of key? [duplicate]

If I have an array like this:
var arr = ['one','two','three'];
I can access different parts by doing this:
console.log(arr[1]);
How can I access object properties by their order rather than by key?
Example:
var obj = {
'something' : 'awesome',
'evenmore' : 'crazy'
},
jbo = {
'evenmore' : 'crazy',
'something' : 'awesome'
};
How would I get the first property for each object–"something" from obj and "evenmore" from jbo–without explicitly using the property name?
Now, a few of you seem to think I'm after something like:
console.log(obj['something']);
This is not the case, I'm specifically looking to target the index, just like the first example - if it's possible.
"I'm specifically looking to target the index, just like the first example - if it's possible."
No, it isn't possible.
The closest you can get is to get an Array of the object's keys, and use that:
var keys = Object.keys( obj );
...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:
keys[ 0 ]; // 'evenmore'
keys[ 1 ]; // 'something'
The only way I can think of doing this is by creating a method that gives you the property using Object.keys();.
var obj = {
dog: "woof",
cat: "meow",
key: function(n) {
return this[Object.keys(this)[n]];
}
};
obj.key(1); // "meow"
Demo: http://jsfiddle.net/UmkVn/
It would be possible to extend this to all objects using Object.prototype; but that isn't usually recommended.
Instead, use a function helper:
var object = {
key: function(n) {
return this[ Object.keys(this)[n] ];
}
};
function key(obj, idx) {
return object.key.call(obj, idx);
}
key({ a: 6 }, 0); // 6
You can use the Object.values() method if you dont want to use the Object.keys().
As opposed to the Object.keys() method that returns an array of a given object's own enumerable properties, so for instance:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
Would print out the following array:
[ 'a', 'b', 'c' ]
The Object.values() method returns an array of a given object's own enumerable property values.
So if you have the same object but use values instead,
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.values(object1));
You would get the following array:
[ 'somestring', 42, false ]
So if you wanted to access the object1.b, but using an index instead you could use:
Object.values(object1)[1] === 42
You can read more about this method here.
var obj = {
'key1':'value',
'2':'value',
'key 1':'value'
}
console.log(obj.key1)
console.log(obj['key1'])
console.log(obj['2'])
console.log(obj['key 1'])
// will not work
console.log(obj.2)
Edit:
"I'm specifically looking to target the index, just like the first example - if it's possible."
Actually the 'index' is the key. If you want to store the position of a key you need to create a custom object to handle this.
Yes, it is possible. We can define getters for each index, and return the property value, in the constructor method of the class. See this code.
class className {
constructor() {
this.name = "Bikram";
this.age = 8;
this.x = 89;
this.y = true;
//Use a for loop and define the getters (with the object property's index as its "name") for each property using Object.defineProperty()
for (let i = 0; i < Object.keys(this).length; i++) {
Object.defineProperty(this, i, {
get: function() {
return Object.values(this)[i]}
});
}
}
}
var b = new className();
console.log(b[0]); // same as b.name ("Bikram")
console.log(b[1]); // = b.age (8)
console.log(b[2]); // = b.x (89)
console.log(b[3]); // = b.y (true)
Edit: If you want to change the properties by their indices, which, of course, you do. Then, just define a corresponding setter for each property in the Object.defineProperty() method. It will look like:
// Insert this in place of the old one
Object.defineProperty(this, i, {
get: function() {
return Object.values(this)[i];
},
set: function(newValue) {
this[Object.keys(this)[i]] = newValue;
}
})
console.log(b[0]); // "Bikram"
b[0] = "Bikram Kumar";
console.log(b[0]); // "Bikram Kumar"
And now you have an "array-like-object" whose properties can be accessed or modified either by property key or its index :D
A side note: Notice that Object.keys() and Object.values() only return the enumerable properties. If you just declare a property and not assign it to any value, the Object.[key/value]s() methods will leave that in the returned array, because by default they are not enumerable. This might become confusing for the indices so defined (except the case the undeclared property is the last one).
To get around this, there is a simple way, if you want some property to have a index, but don't wanna assign it now. Just set it to undefined, and it will now be enumerable, and the indices won't be affected.
by jquery you can do this:
var arr = $.map(obj,function(value, key) {
return value;
});
alert(obj[0]);
Get the array of keys, reverse it, then run your loop
var keys = Object.keys( obj ).reverse();
for(var i = 0; i < keys.length; i++){
var key = keys[i];
var value = obj[key];
//do stuff backwards
}
you can create an array that filled with your object fields and use an index on the array and access object properties via that
propertiesName:['pr1','pr2','pr3']
this.myObject[this.propertiesName[0]]
I went ahead and made a function for you:
Object.prototype.getValueByIndex = function (index) {
/*
Object.getOwnPropertyNames() takes in a parameter of the object,
and returns an array of all the properties.
In this case it would return: ["something","evenmore"].
So, this[Object.getOwnPropertyNames(this)[index]]; is really just the same thing as:
this[propertyName]
*/
return this[Object.getOwnPropertyNames(this)[index]];
};
let obj = {
'something' : 'awesome',
'evenmore' : 'crazy'
};
console.log(obj.getValueByIndex(0)); // Expected output: "awesome"
Sure it is possible, but it is not as immediate as accessing to an array by its indexes, but still possible and even relatively simple actually: in fact you don't have to struggle too much. This code sample will show how:
var obj = {
'alfa' : 'value of obj the key alfa',
'beta' : 'value of obj the key beta',
'gamma' : 'value of obj the key gamma'
};
var jbo = {
'alfa' : 'value of jbo the key alfa',
'beta' : 'value of jbo the key beta',
'gamma' : 'value of jbo the key gamma'
};
alert ( obj[Object.keys(obj)[1]] );
alert ( jbo[Object.keys(jbo)[1]] );
/* you can even put it into a for loop as follows */
for (i=0;i<3;i++)
{
document.writeln ( "<br>This could be even a piece of HTML: " + obj[Object.keys(obj)[i]] );
document.writeln ( "<br>This could be even a piece of HTML: " + jbo[Object.keys(jbo)[i]] );
}
Explication:
As you know the Object.keys() statement returns an array of all enumerable properties (which means all keys) of the object you type into its round parenthesis.
So the only thing you need is to indicate the index after that array, which will returns the key literal found at that index.
The key itself is "digested" as usual by the object which returns the value at that key.
If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead
var keys = []
var obj = {
'key1' : 'value1',
'key2' : 'value2',
'key3' : 'value3',
}
for (var key in obj){
keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])
You can also construct a function that will return the value of a property by accepting two parameters: the object and the "index" (order position)
function getValue(obj, index) {
let keysArray = Object.keys(obj)
let key = keysArray[index]
return obj[key]
}
Usage example getValue(obj, 2)
Snippet
let obj = {a: 'dog', b: 'cat', c: 'mouse'}
function getValue(obj, index){
let keysArray = Object.keys(obj)
let key = keysArray[index]
return obj[key]
}
console.log(getValue(obj, 2))

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