Get second level value from an object with a variable [duplicate] - javascript

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I am making a function where i give the object path in a variable. I use this function after i got my data from the database.
function find(object, path, cb) {
return cb(object[path]);
}
var object = {user:{firstname:"bob"}};
find(object, "user", function(data){});
This works fine with objects on the first level of the object but what if i want a object from the second level or higher:
"user.firstname"
When i try to run this through the find function wil it give a not defined error. How can i improve my function?

You can do it manually by split function and iteratively executing this pattern:
var properties = path.split(".");
var value = obj;
for(prop of properties)
{
value = value[prop];
}

You could make your find function recursive. Besides making the path an array instead of a string gives you the option to do this for multiple layers.
function find (object, path, cb) {
if (path.length > 1) return find(object[path.shift()], path, cb);
return cb(object[path.pop()]);
}
var object = {user: {firstname:"bob"}};
find(object, ["user","firstname"], function (data){console.log(data)});

Related

Search Key/Value Inside Nested Objects (JavaScript) [duplicate]

This question already has answers here:
Recursive function does not return specified value
(2 answers)
Search recursively for value in object by property name
(13 answers)
Closed 2 years ago.
I'm trying to find a object value inside a nested object, this object has a lot o level's and this specific object value that i want it's not always in the same level inside the object.
What i'm trying to do is:
//ArrayofCoordinates it's the array of the objects that i want to search my value inside of each of this objects.
let coordinatesToAddArray = [];
arrayOfCoordinates.map(coordinateObject => {
let coordinateData = findObjectNested(coordinateObject, 'tagName', 'text'); //'tagName' it's the key that i'm looking for and 'text' it's the value of the 'tagName' key that i'm looking for.
if(coordinateData) {
coordinatesToAddArray.push(coordinateData);
}
});
//This is the recursive function that i created to search inside the object for the specific value and return him, but all i get from the return of this function it's a undefined.
function findObjectNested(entireObj, keyToFind, valueToFind) {
if(entireObj && entireObj[keyToFind] === valueToFind) {
return entireObj;
} else {
if(entireObj['children'].length > 0) {
entireObj['children'].map(objectsOfChildren => {
findObjectNested(objectsOfChildren, keyToFind, valueToFind);
});
}
}
}
I know that the recursive function it's working because when i replace the "return entireObj" to "console.log(entireObj)" i can see the object that i'm looking for, but when i'm trying to return this object all i get it's a undefined.
I believe that this has something to do with the recursive function.
Anyone can help me with any tips about how to solve this problem?
Thank you so much.

How to find complex objects in an Object from a String (these have to be separeted with dots) - Angular - [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 3 years ago.
I hope you are very well.
I am trying to find an complex object in an Object in Angular from a String (the content of this String is dynamic).
For example:
let variable = {
"name":"Rick",
"family": {
"son":"Andy"
}
};
When I try to read the name attribute, I can find it with the code:
console.log(variable["name"]);
When I try to read the family attribute, I can find it with the code:
console.log(variable["family"]);
However when I try to read the son attribute, I have tried to make with the code:
console.log(variable["family.son"]);
But I have gotten an undefined value, I found that I can use any of the followings codes:
console.log(variable["family"]["son"]);
console.log(variable["family"].son);
But it is not working for me, because I need to search the attribute from a String (the attributes are Dynamics), Does someone know how can I solve this.
The String contains the attribute path, for instance: "family.son" or "family"
Regards.
Try something like this:
const dotPathAccessor = (src, path) => {
const parts = path.split('.');
return parts.reduce((obj, prop) => obj[prop], src);
}
const variable = {
"name": "Rick",
"family": {
"son": "Andy"
}
};
console.log(dotPathAccessor(variable, "family.son"));
// you can use a Proxy object to make it simpler
// with this prototype, you can now get a dot proxy for any object using `object.getDotProxy`
// and access it using dot paths
Object.prototype.getDotProxy = () => new Proxy(variable, {
get(obj, prop) {
return dotPathAccessor(obj, prop);
}
});
const dotProxy = variable.getDotProxy();
console.log(dotProxy["family.son"]);

Going through a object with a variable [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I guess I didnt really know how to ask this question for me to find an answer.
So I have three variables that are going to make this function do what it has to
function gatherDataForGeographic(ele) {
var $this = $(ele)
var $main_title = $this.find('.options-title'),
$option = $this.find('.option');
var arr = []
var reportAreas = reportManager.getReportAreasObject();
$option.each(function () {
var $this = $(this)
var $checkbox = $this.find('.checkbox');
var type = $this.data('type'),
index = $this.data('index');
if ($checkbox.hasClass('checkbox--checked')) {
console.log(reportAreas.type)
} else {
return true;
}
})
return arr;
}
//this will return an object that I need to index
var reportAreas = reportManager.getReportAreasObject();
//this will get the a key that i need from the object
var type = $this.data('type');
//this will give me the index I need to grab
var index = $this.data('index');
So what I am trying to do is go through the object based on the type(or key) from the option selected by a user
The problem...
It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist.
Is there a way for it to see that type is a variable and not a key?
You can use dynamic properties in JS using the bracket syntax, not the dot syntax:
reportAreas[type]
That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.
reportArea[type][index]
JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation.
object['a']
and
object.a
Are the same thing, basically.

Return object in array with specific property [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 months ago.
I'm fairly new with writing my own JS functions, and I'm struggling with this one.
I want to run through an array of objects, find an object that matches a particular ID, and then return that object.
So far this is what I have:
var findTeam = function() {
$scope.extraTeamData.forEach(team) {
if(team.team_id === $scope.whichTeam) { return team }
}
$scope.thisTeam = team;
};
$scope.teamDetails is my array, and the $scope.whichTeam variable holds the correct ID which I am checking against.
Ultimately I want to be able to assign the object that results from the function to the $scope.thisTeam variable, so I can call its properties in the view.
Any help would be appreciated.
Thanks.
You could use Array#some which ends the iteration if found
var findTeam = function() {
$scope.extraTeamData.some(function (team) {
if (team.team_id === $scope.whichTeam) {
$scope.thisTeam = team;
return true;
}
});
};
Move your $scope.thisTeam = team; to within the if check.
var findTeam = function() {
$scope.teamDetails.forEach(team) {
if(team.team_id === $scope.whichTeam) {
$scope.thisTeam = team;
}
}
};
$scope.team = $scope.teamDetails.filter(function (team) {
return team.team_id === $scope.whichTeam;
})[0];
You need to use filter method of array. It creates new array elements that match given predicate (function that return boolean value). Then you simply take first value.
You can also use find, but it is not implemented in every browser yet.
It would look something like this:
$scope.team = $scope.teamDetails.find(function (team) {
return team.team_id === $scope.whichTeam;
});

How do you access an object within an object from an argument in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Accessing nested JavaScript objects with string key
I have the function
function _get(name) {
return plugin._optionsObj[name] !== undefined ?
plugin._optionsObj[name] : plugin._defaults[name];
}
I would like to be able to have objects inside of my _defaults object, but then I don't know how to retrieve them but using just one set of square brackets.
i.e.
plugin._defaults = {
val1: 1,
val2: 2,
obj1: {
someVal: 3
}
}
Is it possible to access 'someVal' from the function I have above? I tried passing 'obj1.someVal' for the argument and it didn't work. Ideas?
Edit: I have found a solution and I posted it below as an answer. I've written a very nice little function to do go through the nested values with a string and I didn't have to change my function much to implement it. I hope this helps anyone in a similar situation.
I suspect that you won't always have a one-level nested object to access, so the cleaner way to do this is to use a function that traverses an object based on a string path. Here's one that is coded as a mixin for Underscore. You can then just use it like so:
_.deep(plugin._defaults, 'obj1.someVal');
This thread also has some non-Underscore alternatives.
Pass multiple arguments, and iterate over the arguments object.
function _get(/* name1, name2, namen */) {
var item = plugin._optionsObj,
defItem = plugin._defaults;
for (var i = 0; i < arguments.length; i++) {
item = item[arguments[i]];
defItem = defItem[arguments[i]];
if (item == null || defItem == null)
break;
}
return item == null ? defItem : item;
}
var opt = _get("obj1", "someVal")
I found a solution for this problem, at least one that will accommodate myself, and I'd like to share it in case it can help someone else with this problem. My biggest difficulty is that I did not know the depth of the nested value so I wanted to find a solution that would work for deeply nested objects and without requiring to redesign anything.
/* Retrieve the nested object value by using a string.
The string should be formatted by separating the properties with a period.
#param obj object to pass to the function
propertyStr string containing properties separated by periods
#return nested object value. Note: may also return an object */
function _nestedObjVal(obj, propertyStr) {
var properties = propertyStr.split('.');
if (properties.length > 1) {
var otherProperties = propertyStr.slice(properties[0].length+1); //separate the other properties
return _nestedObjVal(obj[properties[0]], otherProperties); //continue until there are no more periods in the string
} else {
return obj[propertyStr];
}
}
function _get(name) {
if (name.indexOf('.') !== -1) {
//name contains nested object
var userDefined = _nestedObjVal(plugin._optionsObj, name);
return userDefined !== undefined ? userDefined : _nestedObjVal(plugin._defaults, name);
} else {
return plugin._optionsObj[name] !== undefined ?
plugin._optionsObj[name] : plugin._defaults[name];
}
}
To retrieve objects inside of your _defaults object you'll need to improve your _get function.
For example you may pass an array of strings (each string representing a propery name) to _get to allow access to deeply nested objects.

Categories