Search recursively for value in object by property name
You could use Object.keys
and iterate with Array#some
.
function findVal(object, key) { var value; Object.keys(object).some(function(k) { if (k === key) { value = object[k]; return true; } if (object[k] && typeof object[k] === 'object') { value = findVal(object[k], key); return value !== undefined; } }); return value;}
var object = { photo: { progress: 20 }};console.log(findVal(object, 'progress'));
How to find the key of a value in a nested object recursively
After the few questions made above, it looks like the function should:
- Assume the input is always an object.
- Assume it might encounter arrays in its way.
- Assume it must stop after meeting one value (in case multiple value exists).
The provided input code given by the OP does not handle array cases.
Below code is sampled to work with these sample cases:
- Plain nested object structure.
- Object with nested arrays of objects or elements.
Below function accepts a second argument which is a callback to evaluate whether the element met is actually the one we're looking for. In this way, it's easier to handle more complex checks.
The recursive approach is kept and, once the key is met, the function simply return
to avoid unnecessary searchs.
const foo = { data: { data2: { data3: 'worked' }, data21: 'rand' }, data01: 'rand01' };const fooWithArrays = { data: { data2: { data3: 'not here' }, data4: [ { data5: 'worked' }, { data6: 'not me' } ] }};const fooWithExpression = { data: { data2: { data3: { id: 15, name: 'find me!' } }, data21: { data25: 'not me' } }};
const findKeyByValue = (obj, equalsExpression) => { // Loop key->value pairs of the input object. for (var [key, v] of Object.entries(obj)) { // if the value is an array.. if (Array.isArray(v)) { // Loop the array. for (let i = 0; i < v.length; i++) { // check whether the recursive call returns a result for the nested element. let res = findKeyByValue(v[i], equalsExpression); // if so, the key was returned. Simply return. if (res !== null && res !== undefined) return res; } } // otherwise.. else { // if the value is not null and not undefined. if (v !== null && v !== undefined) { // if the value is an object (typeof(null) would give object, hence the above if). if (typeof(v) === 'object') { // check whether the value searched is an object and the match is met. if (equalsExpression(v)) return key; // if not, recursively keep searching in the object. let res = findKeyByValue(v, equalsExpression); // if the key is found, return it. if (res !== null && res !== undefined) return res; } else { // finally, value must be a primitive or something similar. Compare. let res = equalsExpression(v); // if the condition is met, return the key. if (res) return key; // else.. continue. } } else continue; } }}
console.log( findKeyByValue(foo, (found) => found === 'worked') );console.log( findKeyByValue(fooWithArrays, (found) => found === 'worked') );console.log( findKeyByValue(fooWithExpression, (found) => found && found.id && found.id === 15) );
how to recursively find if object key exist?
Something like this will work for you:
//This is your original object
var someObject = {
acn: "02 0002 0002",
id: "random",
name: "random",
parent_domain: "parent-random",
subDomainData: { someObjectWith_subDomainData },
sub_domains: ["random-l3.1"],
timestamp: 1549597441
};
//This will store the list of subDomains in this global variable.
var subDomainList = [];
function getSubDomainList(objectToLoop){
if(objectToLoop.hasOwnProperty('subDomainData')){
var numOfItems = Object.keys(objectToLoop.subDomainData).length;
var keys = Object.keys(objectToLoop.subDomainData);
for(var i = 0; i< numOfItems; i++){
var key = keys[i];
var obj = objectToLoop.subDomainData[key];
subDomainList.push(obj);
getSubDomainList(obj);
}
}
return;
}
getSubDomainList(someObject);
//The subDomainList will have the array of objects.
Track nested object keys with end value recursively
Thanks all for your responses really helped me get there, i ended up with this:
const setCSSVars = (obj: { [key: string]: any }, stack: string[] = []) => {
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === 'object' && value !== null) {
setCSSVars(value, [...stack, key])
} else {
document.documentElement.style.setProperty(
`--theme-${stack.join('-')}-${key}`,
value
)
}
})
}
How recursively get all keys of nested object?
It looks like you want something like this:
type RecursiveKeyof<T> = T extends object ? (
T extends readonly any[] ? RecursiveKeyof<T[number]> : (
keyof T | RecursiveKeyof<T[keyof T]>
)
) : never
This recurses down into object types, giving you the keys of all the subproperties and sub-subproperties, etc. It ignores primitives (so no keyof string
), and special-cases arrays so that you only get keys of the elements of the array and not the array itself (which has keys like number
and "push"
, "pop"
, etc).
Your AllKeys
seems to want a keys
property so we can write it like this:
type AllKeys<T> = { keys: RecursiveKeyof<T> }
Let's see if it works:
type Test = AllKeys<NestedObject>
// type Test = {keys: "amount" | "error" | "data" | "rows" | "messages" | "goodNews" | "badNews" }
Looks good.
Playground link to code
Recursively replace keys within an object of unknown size using Javascript
You could take a recursive approach.
function replace(object) { return Array.isArray(object) ? object.map(replace) : object && typeof object === 'object' ? Object.fromEntries(Object .entries(object) .map(([k, v]) => [k in operators ? operators[k] : k, replace(v)]) ) : object;}
var obj = { where: { hypes: { lte: 12 }, or: [{ hypes: { lt: 'xx' } }, { id: { lt: 10 } }] } };
const operators = { eq: '[Op.eq]', lte: '[Op.lte]', lt: '[Op.lt]', or: '[Op.or]' };
console.log(replace(obj));
Related Topics
Get the Value of Datepicker on Change in Jquery
Calculating Sum of Checked Checkboxes
Show Form Fields Based on Selected Option
Array Map into String With Line Break - React
How to Set the Multi Sliders in One Page
Display a Loading Icon While Images Loads
How to Make Mongoose Not Insert Empty Array or Object Fields into a Document
Create Parent and Child Relationship Using Lodash
How to Expire a Cookie in 30 Minutes Using Jquery
After Clicking a Button of Sweet Alert Call PHP File
How to Update Component State on Redux State Change
Converting Excel Date Serial Number to Date Using JavaScript
Domexception: Play() Can Only Be Initiated by a User Gesture
How to Translate the Following Jquery Code to React
Res.Sendfile in Node Express With Passing Data Along
How to Format Material Datepicker Date Value to "Mm-Dd-Yyy" Format in Angular 6