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

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

Related

How to to make a varargs statement in javascript [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 1 year ago.
In javascript I am in situation where i need to make variable arguments based on a length of an array, below is an sample code
function getValesList(json){
return getValues(json[0])+getValues(json[1])+getValues(json[2]);
}
function getValues(json1){
let valueList = Object.values(json1);
let valueListPipe = valueList.join("|");
return valueListPipe+lineSeparator;
}
where json is an array of JSON objects and I need to make a pipe delimiter file based on the length of incoming array. How to make it dynamic where I can do like a varargs in JAVA
If you're just passing N arguments of the same type, you can use the rest feature of Javascript for function arguments.
function getValuesList(...json){
return json.map(j => getValues(j)).join("");
}
This allows you go pass any number of separate arguments as in getValuesList(o1, o2, o3, o4) and the json parameter within your function will automatically be an array of however many arguments were passed.

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

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"

Using Function Variable to Retrieve Object Literal Value [duplicate]

This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 6 years ago.
I have a function that converts an object literal response data into an array:
From: [{"_id":"1","rating":7},{"_id":"2","rating":3}]
To: [7,3]
function createArray(fieldVar, responseData) {
var newArray = responseData.map(function(data) {
return data.fieldVar // fails here because I am trying to use the fieldVar variable
});
return newArray
};
I call the function like this:
createArray('rating',response.rating_x)
This fails because of the data.fieldVar If I hardcode the call to data.rating it works correctly.
How do I pass in the 'rating' or any other name on the function call?
Try it with brackets
function createArray(fieldVar, responseData) {
var newArray = responseData.map(function(data) {
return data[fieldVar] // access with brackets
});
return newArray
};
When using the dot-notation, the property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), not starting with a number. When you're using variables, you need to use bracket notation, else data.fieldVar would point to the property 'fieldVar' which probably doesn't exist. This is because the variable that you intended to access is not evaluated, but instead treated as a normal "string".
More informations on MDN: Property accessors

Counting length of another object property within object function -- JavaScript? [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 6 years ago.
I am new to JavaScript objects so please bear with me.
This is my JavaScript:
var dragSources = {
elementSources: {
squareSource: document.getElementById('squareSource'),
circleSource: document.getElementById('circleSource')
},
ifDragSource: function(elem) {
console.log(this.elementSources.length);
}
};
If you look at console.log(this.elementSources.length); you can probably tell that I am trying to get the length of the elementSources property. However, it returns undefined. What am I doing wrong?
It's an object, not an array, therefore it doesn't have a length property.
You could use Object.keys(this.elementSources).length to get the number of keys.
The .keys() method essentially returns an array of the object's keys.
In this case, Object.keys(this.elementSources) returns:
["squareSource", "circleSource"]
Then we are just getting the length of that array, which is 2.
var dragSources = {
elementSources: {
squareSource: document.getElementById('squareSource'),
circleSource: document.getElementById('circleSource')
},
ifDragSource: function(elem) {
console.log(Object.keys(this.elementSources).length);
}
};
dragSources.ifDragSource(); // 2
Technically if you need the length property in a code you have to store the length value directly in the object.
Using Object.key function decreases the code efficiency .
every time you invoke that function to access that value you have to re-run the same function again and again.
in order access to the length property in a js array, the BIG O is always equal to 1.
because when you update the array the length property would be updated consequently
But in that case the big O would be in the size of the Object and (O) = n

Categories