Getting an object property value using a dotted string [duplicate] - javascript

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 6 years ago.
I m trying to access an object property through a string.
What I m trying to do is :
const data = {
key: {
subKey: 'value'
}
};
const theString = 'key.subKey';
function accessPropFromString(obj, stringCall) {
// I don't know what to put on here
}
console.log(accessPropFromString(data, theString)) // prints 'value'
I absolutely don't know how to make that happen...
How can I do this kind of stuff with JavaScript ?

You could split the path and reduce the object.
const getValue = (object, path) => path.split('.').reduce((o, k) => (o || {})[k], object),
data = { key: { subKey: 'value' } },
theString = 'key.subKey';
console.log(getValue(data, theString));

This should work. Assuming, you have fixed format.
function accessPropFromString(obj, stringCall) {
var splitter =stringCall.split(".");
return data[splitter[0]][splitter[1]];
}
Demo

See comments inline:
const data = {
key: {
subKey: 'value'
}
};
const theString = 'key.subKey';
function accessPropFromString(obj, stringCall) {
// Split the string into individual parts
var parts = stringCall.split(".");
// You can use strings to lookup properties on objects
// if you use bracket notation, like this;
// parts["key"]["subKey"]
// So, parts[0] will be "key" and parts[1] will be "subKey"
return obj[parts[0]][parts[1]];
}
console.log(accessPropFromString(data, theString)) // prints 'value'

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

How to make key a variable in firebase updates with React [duplicate]

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.
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.
Heres the situation:
I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this:
[ { key: '1' }, { key: '1' } ]
(.map() returns an array of objects fyi)
I need key to actually be the string from this.attr('name').
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).

How to conditionally create object property in one line? [duplicate]

This question already has answers here:
In JavaScript, how to conditionally add a member to an object?
(29 answers)
Conditionally set an object property
(7 answers)
How to conditionally add properties to a javascript object literal
(8 answers)
Closed 8 months ago.
I want to create a property on an object conditionally.
The idea is to ensure the property doesn't exist (so not just null) if it has no value.
What I'm doing right now:
// comes from users
req.query = {
foo: true
}
// my object which will contains allowed properties IF EXISTS
const where = {}
if (req.query.foo) {
where.foo = req.query.foo
}
if (req.query.bar) {
where.bar = req.query.bar
}
console.log(where)
It's really boring to repeat this for every different property...
Is there a way to do it in one line?
EDIT:
I don't want to get all properties from req.query
Create object property obj.foo if value exists (or any other condition)
&& operator returns second element if the first boolean condition is fulfilled
es6 spread operator ... does what it does)
const value = 'bar'
const empty = undefined
const obj = {
...value && { foo: value }, // read ...(value && { foo: value }) parenthesis are not necessary
...empty && { empty },
...(100 > 0) && { condition: 'true' },
...(100 < 0) && { condition: 'false' },
}
console.log(obj)
You could do:
const merged = {...where, ...req.query};
Try this:
const elements = ["foo", "bar"];
elements.forEach(el => {
if (req.query[el]) {
where[el] = req.query[el];
}
});
You can simply write it in one line like this :
let where = {};
if (req.query.foo) where = {...where, foo : req.query.foo };
if (req.query.bar) where = {...where, bar : req.query.bar };
I hope that it helps.
If you want a simple one liner (maybe less readable), you can do:
Object.keys(req.query).forEach(key => req.query[key] && (where[key] = req.query[key]));
If you're okay adding a pluck function, you could do it like this:
const req = { query: { baz: '1', foo: '3' } };
const where = {};
const pluck = (keys, obj) =>
keys.reduce((a, k) => typeof obj[k] === 'undefined' ? a : Object.assign(a, { [k]: obj[k] }), {});
const add_foo_bar = (where, query) =>
Object.assign({}, where, pluck(['foo', 'bar'], query));
const res = add_foo_bar(where, req.query);
console.log(res);

Loop through nested objects from string input [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 3 years ago.
Let's say I have a string like 'user.data', and I want to create the data field of this object:
const obj = {
user: {
data: {}
}
}
I am not able to do this normally (obj['user.data'] = {}) with this string because it will do this:
const obj = {
user: {},
'user.data': {}
}
And that is not what I am looking for.
How would I go about creating a property with an object when that is the last part of the string?
const str = 'user.hobbies';
const obj = { user: {} };
addInNestedProp(str, obj);
console.log(obj);
// => { user: { hobbies: {} } }
Here is a solution that will allow you to take a string such as "user.hobbies", evaluate an object against that string, and add any properties to the object that are in the string, but not in the object.
Using your input string "user.hobbies" will produce:
{
"name": "me",
"user": {
"avatarURL": "longURL",
"hobbies": {}
}
}
You can also try this with "user.hobbies.sports.basketball" and it will produce the object hierarchy you expect.
The code is heavily documented:
const existing = { name: 'me', user: { avatarURL: 'longURL' }};
const addInHobbyString = 'user.hobbies';
const newObject = addInObject(addInHobbyString, existing);
console.log(newObject);
function addInObject(term, obj) {
// make a clone of the object
let objCopy = JSON.parse(JSON.stringify(obj));
// separate serach terms
let terms = term.split('.');
// set temp obj to first search term as object property
// any modifications to temp will be seen in objCopy
let temp = objCopy[`${terms[0]}`];
// Find the last search term that exists as an object property
let q = terms.reduce((acc, curr, idx) => (objCopy[`${curr}`]) ? null : idx, 0);
// Do the work
for (let i = 1; i <= q; i++) {
// if property doesn't exist on object create it and set it to an empty object
if (!temp[`${terms[i]}`]) {
temp[`${terms[i]}`] = {};
// Set the search depth in our temp object to the next depth
temp = temp[`${terms[i]}`]
}
}
return objCopy;
}

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