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.
Related
This question already has answers here:
Dynamically creating keys in a JavaScript associative array
(10 answers)
Closed 5 days ago.
I am trying to create a function “updateProp” that has the following parameters:
“obj” - an object to update
“keyName” - a key name to update on the object
“val” - the new value to assign to the key
“updateProp” should update the object passed in based on the “keyName” and “val” pair given and should return the object that was passed in
I started with:
function updateProp(obj, keyName, val){
}
I am expecting a result such as:
const wallet = {
color: 'Black',
hasCash: true
}
updateProp(wallet, 'color', 'Blue'); => { color: 'Blue', hasCash: true }
I don’t know how I should write out the function in order for it to perform the action I want above
Need to assign object key that value like this
function updateProp(obj, keyName, val){
obj[keyName]=val
}
This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed last year.
I have a code which would be very repetitive, which according to the name of the string of an array executes one function or another.
I give an example of a code as I could do it.
// I use underscore in NodeJS
_.each(refresh, (value, key) => {
if(key === 'station') {
station.add({ id: value });
} else if(key === 'concentrator') {
concentrator.add({ id: value });
} else if....
});
It is possible to run the function according to your string to avoid so much checking with IF, etc.
[key].add({ id: value });
I have been watching several hours on the internet about the use of call, apply, etc; but I do not understand how it works well, perhaps because my knowledge of Javascript is not advanced.
Thanks !
Creating an anonymous function on an object is the best approach. As you can use the key to call the method.
Here is an example in code pen:
https://codepen.io/liam-hamblin/pen/KKyapNP
The code above takes in the key used to assign the function and does not require any checks. However, it is always the best approach to check that the key exists before calling.
const operations = {};
operations.add = (obj) => {
document.write("add - ");
document.write(JSON.stringify(obj));
}
operations.subtract = (obj) => {
document.write("subtract - ");
document.write(JSON.stringify(obj));
}
const input = prompt("Enter Function Name, type either subtract or add");
if (operations[input]) {
operations[input]({id:1});
} else {
document.write("no matching method")
}
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;
});
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)});
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.