Given the path of property key, how to retrieve it? [duplicate] - javascript

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"

Related

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

How to add item to object JS [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I have looked all over google and i have found nothing that fits my needs. How would you add an item to an object. I basically have a string variable that i want as the key. Therefore i cant use obj.key = 'something';. I sort of want it like:
obj = {'somekey': 'somevalue'};
obj.add('someotherkey': 'someothervalue');
console.log(obj);
by obj.add() i mean someone's solution
and then console says {'somekey': 'somevalue', 'someotherkey': 'someothervalue'}
Does anyone know a way to do this. I don't care at what position it is just whether it is there. By the way i'm using node if that helps. If you have any questions on my code please ask.
Very simple:
obj["somekey"] = "somevalue";
You can also use a variable instead:
let myVariable = "somekey";
obj[myVariable] = "somevalue";
Or you just use normal object notation:
obj.somekey = "somevalue"

Reference nested json object property by string [duplicate]

This question already has answers here:
Access object child properties using a dot notation string [duplicate]
(13 answers)
Closed 3 years ago.
I know I'm missing something obvious here but say I have a JSON object that looks like this:
testObj = {
levelOne: {
levelTwo: []
}
}
I also have a string value:
var prop = 'levelOne.levelTwo';
I'm trying to determine if there's any way to basically do something like this:
var x = testObj[prop];
That doesn't work, but is there any way to do the equivalent?
There's no trivial way (e.g. testObj[prop]) of doing this, but the reduce function is well suited:
let nestedProp = (obj, path) =>
path.split('.').reduce((obj, prop) => obj[prop], obj);
let x = nestedProp({levelOne: {levelTwo: [5]}}, 'levelOne.levelTwo');
console.log(x);
You can use dynamic keys to access properties in an object but not multiple levels down.
i.e. You can do const a = testObject["levelOne"] but not what you tried. (Docs)
There are however helper libs that have functions to do this. One example is lodash.get function

Is there any clean way of initializing an object with a variable key? [duplicate]

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

JavaScript Calling Object Syntax [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I need to know why this isn't working. My Javascript code accesses a variable in an object. But it appears not to be working, partly because I can't figure out the syntax.
var obj = {
size:"small",
big:false,
thing:true
}
alert(obj[size]);
I'm just not sure if I got the syntax right…
This will work here.
obj.size //returns small
OR
obj["size"] //returns small
OR
var my_var = "size"
obj[my_var] //returns small
You can reference object values either by:
obj["size"]
or
obj.size
However, there is an exception. For instance, if you have following object with a number key: (Note: key is still a string even if it's defined this way):
var obj = {
1: true
};
You can retrieve it's value only by using: obj["1"]
Hence, using obj.1 will cause a syntax error.
Therefore, your code works if you change it to e.g.: alert(obj["size"]); but I prefer to use console.log(obj["size"]); for debugging. At least, if you are playing with node.js as your tags indicates.
Cheers.

Categories