Reference nested json object property by string [duplicate] - javascript

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

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 access value in Object? [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 3 years ago.
I have this Array Object that looks like this:
let arr = [
{Name: "sub", Value: "ababbnnn"}
]
I'm trying to access the value of the Name custom:network meaning I want to output this: abcdef1233bfgh. So far I have this loop but I wonder if there may be a cleaner way. Thanks a lot in advance. Here's my code:
You can use the find method:
const value = arr.find(item => item.Name === "custom:network").Value
To cover the case where no item is returned by find, you can use the following approach:
const value = (arr.find(item => item.Name === "custom:network") || {}).Value

Get from JSON object with string IDs to JS numeric IDs [duplicate]

This question already has answers here:
Is there any way to use a numeric type as an object key?
(11 answers)
Closed 4 years ago.
i have a JSON object (sent from php) and I want to convert the IDs to a numeric key using JS. So currently it looks something like that:
let foo = {"66":"test","65":"footest"};
And now I want it to look like this:
let foo = {66:"test",65:"footest"};
Object keys do not need to be numerical to be accessed - as noted in the comments - they are strings regardless.- Below, I am console logging the "66" property using the brackets notation - foo[66]
let foo = {"66":"test","65":"footest"};
console.log(foo[66]); // gives "test"
// if you want to assign values numerically - ie using the index of a loop - then you could do
for(i = 63; i<65; i++) {
foo[i] = "test" + i;
}
console.log(foo); // gives {"63": "test63", "64": "test64","65": "footest","66": "test"}

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

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"

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

Categories