ESLint error use Object.keys instead of for..in - javascript

I'm working on the below code which works perfectly fine. But, ESLint suggest to use Object.keys instead of for..in loop. I tried to iterate the keys, do the search if the match found then return the object. It works with for..in but not with Object.keys. I tried to replace forEach with filter but didn't work for me. Any suggestions.
function searchObj (obj, query) {
// Object.keys(obj).forEach(function(key){
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object') {
return searchObj(value, query);
}
if (typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1) {
return obj;
}
}
}
var demoData=[
{id:1,desc:{original:'trans1'},date:'2017-07-16'},
{id:2,desc:{original:'trans2'},date:'2017-07-12'},
{id:3,desc:{original:'trans3'},date:'2017-07-11'},
{id:4,desc:{original:'trans4'},date:'2017-07-15'}
];
var searchFilter = demoData.filter(function(obj){
return searchObj(obj, 'trans1');
});
console.log(searchFilter);
here is the link JS bin

Since you don't really use found object just the fact it is there. You could use Array.prototype.some to avoid looping over every key in obj is you have already found it matches the search query.
function searchObj (obj, query) {
return Object.keys(obj).some(function(key) {
var value = obj[key];
if (typeof value === 'object') {
return searchObj(value, query);
}
return typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1;
});
}
var demoData=[
{id:1,desc:{original:'trans1'},date:'2017-07-16'},
{id:2,desc:{original:'trans2'},date:'2017-07-12'},
{id:3,desc:{original:'trans3'},date:'2017-07-11'},
{id:4,desc:{original:'trans4'},date:'2017-07-15'}
];
var searchFilter = demoData.filter(function(obj){
return searchObj(obj, 'trans1');
});
console.log(searchFilter);

When you use Object.keys with forEach to iterate through the keys, you are passing a function as callback, so the return statements are for that callback function instead of searchObj.
Instead of returning the result from the forEach callback, you can store it in an external variable (accessed inside the forEach by means of closure), assign it in the forEach, and then return its value. Here I create a variable called foundObj for that:
function searchObj (obj, query) {
var foundObj = null;
Object.keys(obj).forEach(function(key) {
var value = obj[key];
if (typeof value === 'object') {
foundObj = searchObj(value, query);
}
if (typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1) {
foundObj = obj;
}
});
return foundObj;
}
var demoData=[
{id:1,desc:{original:'trans1'},date:'2017-07-16'},
{id:2,desc:{original:'trans2'},date:'2017-07-12'},
{id:3,desc:{original:'trans3'},date:'2017-07-11'},
{id:4,desc:{original:'trans4'},date:'2017-07-15'}
];
var searchFilter = demoData.filter(function(obj){
return searchObj(obj, 'trans1');
});
console.log(searchFilter);

Related

Typescript .forEach and for in behavior

I made a Typescript playground to show you the code and the output. I don't understand why I don't have the same result in my code when I'm using .forEach and for in loop.
I made 2 functions to trim all body parameters. The first function use .forEach() and the 2nd use for in.
Here is the functions:
function trimWithForEach(obj: any): any {
if (obj !== null && typeof obj === 'object') {
Object.keys(obj).forEach(function (prop) {
// if the property is an object trim it
if (typeof obj[prop] === 'object') {
return trimWithForEach(obj[prop]);
}
// if it's a string remove begin and end whitespaces
if (typeof obj[prop] === 'string') {
obj[prop] = obj[prop].trim();
}
});
}
}
function trimWithForIn(obj: any): any {
if (obj !== null && typeof obj === 'object') {
for (var prop in obj) {
// if the property is an object trim it
if (typeof obj[prop] === 'object') {
return trimWithForIn(obj[prop]);
}
// if it's a string remove begin and end whitespaces
if (typeof obj[prop] === 'string') {
obj[prop] = obj[prop].trim();
}
}
}
}
With the forEach() I have the good result that I want, it will trim all my body. But with for in I have a problem because only the first object conditon is triggered to make my recursive call and if I have other object types they are ignored. The recursive call works only once in all my body object in the for in loop and I don't know why.
Can you help me to understand ?
In for..in loop the return is returning you out of function at the very first time it encounters the condition to be true. That's why the later items never get processed.
I am not quite sure what you are trying to do here but there is a basic difference between the way 'forEach' and 'for...in' works with regards to 'return'.
In for...in return returns the value out of function, but in forEach the return doesn't work.
Look at the following simple example for more clarity
var testfn = function() {
let a = [1,2,3]
let b = a.forEach(el => {
if ( el == 2 )
return el
})
console.log("Came here!")
console.log({b})
}
var testfn1 = function() {
let a = [1,2,3]
for ( let i in a ){
if ( a[i] == 2 )
return a[i]
}
console.log("Came here!")
console.log({a})
}
testfn()
testfn1()

Map and return a new object instead of deleting existing data recursively

I have the following logic which goes in and switches all nested Object keys to camel case.
It works fine but I am currently deleting existing data in the object I am converting from.
Is there a way I could have mapped this instead and return a new object without affecting the initial object?
This is the working one where I am modifying the object being passed.
const convert = (data, caseType) => {
Object.keys(data).forEach((previousKey) => {
let newKey = case(previousKey);
if (newKey !== previousKey) {
data[newKey] = data[previousKey];
delete data[previousKey];
}
if (typeof (data[newKey]) === 'object' || data[newKey] === Array) {
data[newKey] = convert(data[newKey]);
}
});
return data;
};
You can use Object.entries to get the entries, map to create your new structure, and then build the new object using Object.fromEntries, like this:
const convertAllObjectKeyCase = (data, caseType) => {
if (typeof data !== "object" || data === null) return data;
return Object.fromEntries(
Object.entries(data).map(([previousKey, value]) => {
let newKey;
switch (caseType) {
case SNAKE_CASE:
newKey = snakeCase(previousKey);
break;
default:
newKey = camelCase(previousKey);
break;
}
// This condition looks suspect to me −−−vvvvvvvvvvvvvvv
if (typeof value === "object" || value === Array) {
value = convertAllObjectKeyCase(value);
}
return [newKey, value];
})
);
};
Or use a for-in loop and build the new object as you go:
const convertAllObjectKeyCase = (data, caseType) => {
if (typeof data !== "object" || data === null) return data;
const result = {};
for (const previousKey in data) {
// This matches with your previous use of `Object.keys`, which
// skips inherited properties
if (!Object.prototype.hasOwnProperty.call(data, previousKey)) {
continue;
}
let value = data[previousKey];
let newKey;
switch (caseType) {
case SNAKE_CASE:
newKey = snakeCase(previousKey);
break;
default:
newKey = camelCase(previousKey);
break;
}
// This condition looks suspect to me −−vvvvvvvvvvvvvvvv
if (typeof value === "object" || value === Array) {
value = convertAllObjectKeyCase(value);
}
result[newKey] = value;
}
return result;
};
In a comment you've said:
'This condition looks suspect to me'. i am checking if the value is another array or obj, get into there too to switch case for those nested ones.
x === Array checks to see if x is the Array constructor function, not if it's an array. If you want to handle arrays, you'll want to change that to Array.isArray(x) and change the logic of the function to handle arrays (since currently it assumes everything is a non-array object).
In both of the previous examples, to handle arrays, you can change this:
// This condition looks suspect to me −−−vvvvvvvvvvvvvvv
if (typeof value === "object" || value === Array) {
value = convertAllObjectKeyCase(value);
}
to this:
if (typeof value === "object" && value !== null) {
value = convertAllObjectKeyCase(value);
} else if (Array.isArray(value)) {
// Convert any objects in the array
value = value.map(convertAllObjectKeyCase);
}
Or to avoid having the same logic in two places, just rely on the fact that convertAllObjectKeyCase checks for objects:
value = Array.isArray(value)
? value.map(convertAllObjectKeyCase)
: convertAllObjectKeyCase(value);
Or even have convertAllObjectKeyCase handle arrays as well as objects by changing it to just:
value = convertAllObjectKeyCase(value);
and adding this just after the object/null check at the beginning:
if (Array.isArray(data)) {
return data.map(convertAllObjectKeyCase);
}

Check if key exists in object **at any level** [duplicate]

I'm building an utility function that should search for a property name and return its value once it is found. It should do this recursively:
// Function
util.findVal = (object, propName) => {
for (let key in object) {
if (key === propName) {
console.log(propName)
console.log(object[key])
return object[key]
} else {
util.findVal(object[key], propName)
}
}
}
// Input
object: {
photo: {
progress: 20
}
}
// Usage
util.findVal(object, 'progress')
However the console log goes forever and the browser crashes. What am I doing wrong?
EDIT:
This is how I'm calling the function:
// Input
item: {
photo: {
file: {},
progress: 20
}
}
this.findProgress(item)
methods: {
findProgress (item) {
return util.findVal(item, this.propName)
}
}
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'));
Your code has a few errors:
You're recursively calling util.findVal but not returning the result of the call. Code should be return util.findVal(...)
You're not passing the attribute name key to the recursive call
You're not handling the possibility of a reference loop
If an object contains a key and also a sub-object that contains the key which value is returned is random (depends on the sequence in which the keys are analyzed)
The third problem is what can cause infinite recursion, for example:
var obj1 = {}, obj2 = {};
obj1.x = obj2; obj2.y = obj1;
if you just keep looking recursively searching in obj1 or obj2 could lead to infinite recursion.
Unfortunately for reasons not clear to me in Javascript is impossible to know the object "identity"... (what Python id(x) does) you can only compare an object to another. This means that to know if an object has already been seen in the past you need a linear scan with known objects.
ES6 added the possibility to check object identity with Set and Map where objects can be used as keys. This allows for faster (sub-linear) search times.
A search solution that runs in depth order could be for example:
function findVal(obj, key) {
var seen = new Set, active = [obj];
while (active.length) {
var new_active = [], found = [];
for (var i=0; i<active.length; i++) {
Object.keys(active[i]).forEach(function(k){
var x = active[i][k];
if (k === key) {
found.push(x);
} else if (x && typeof x === "object" &&
!seen.has(x)) {
seen.add(x);
new_active.push(x);
}
});
}
if (found.length) return found;
active = new_active;
}
return null;
}
given an object and an attribute name, returns all the values found with that name at the first depth they are found (there can be more than one value: for example when searching {x:{z:1}, y:{z:2}} for the key "z" two values are at the same depth).
The function also correctly handles self-referencing structures avoiding infinite search.
Don't write your own utility if you can avoid it.
Use something like jsonpath
Some examples of supported syntax:
JSONPath Description
$.store.book[*].author The authors of all books in the store
$..author All authors
$.store.* All things in store, which are some books and a red bicycle
$.store..price The price of everything in the store
$..book[2] The third book
$..book[(#.length-1)] The last book via script subscript
$..book[-1:] The last book via slice
$..book[0,1] The first two books via subscript union
$..book[:2] The first two books via subscript array slice
$..book[?(#.isbn)] Filter all books with isbn number
try changing else statement like this
return util.findVal(object[key],propName)
I know this is an old post, but I found it helpful to answer a problem I had with recursively finding a value by it's key. I further developed the answer given by Nina Scholz, and came up with the following. It should be quicker as it is not creating an array of all of the keys each time it is recursively invoked. Also, this will explicitly return false if the key is not found.
function findVal(obj, keyToFind) {
if (obj[keyToFind]) return obj[keyToFind];
for (let key in obj) {
if (typeof obj[key] === 'object') {
const value = findVal(obj[key], keyToFind);
if (value) return value;
}
}
return false;
}
var object = { photo: { progress: 20 }};
console.log(findVal(object, 'progress'));
I think you are saying that you want to look for the property name anywhere recursively within the objects tree of properties and sub-properties. If so, here is how I would approach this:
var object1 = _getInstance(); // somehow we get an object
var pname = 'PropNameA';
var findPropertyAnywhere = function (obj, name) {
var value = obj[name];
if (typeof value != 'undefined') {
return value;
}
foreach(var key in obj) {
var v2 = findPropertyAnywhere(obj[key], name);
if (typeof v2 != 'undefined') {
return v2;
}
}
return null;
}
findPropertyAnywhere(object1, pname);
Think about it if there is no key found.
I think you could do something like this instead of search
return object[propName] || null
In your code there was a breakpoint missing, I guess you are trying to search inside the whole object not just the directly related attributes so here is an edit for you code
EDIT:
util.findVal = (object, propName) =>{
if(!!object[propName]){
return object[propName]
}else{
for (let key in object) {
if(typeof object[key]=="object"){
return util.findVal(object[key], propName)
}else{
return null
}
}
}
}
Found this question in the realm of needing a general solution to check if an object contains a specific value anywhere in its hierarchy (regardless of the key), which can include arrays of course. So the following does not answer OPs question directly or improve upon other solutions but it might help others looking for the same thing I did and finding this post:
function hasValue(object, value) {
return Object.values(object).some(function(val) {
if (val === value) {
return true;
}
if (val && typeof val === 'object') {
return hasValue(val, value);
}
if (val && val.isArray()) {
return val.some((obj) => {
return hasValue(obj, value);
})
}
});
}
it is of course inspired by #Nina Scholz 's solution!
An answer depends a on how complex you want to get. For example a JSON parsed array doesn't contain functions - and I'm fairly certain it won't contain property value set to a parent node in object tree.
This version returns the property value of the first property name found whilst searching the object tree. undefined is returned if either the named property was not found or has a value of undefined. Some modifications would be needed to tell the difference. It does not re-search parent nodes already being searched, nor try to scan null objects!
let util = {};
util.findVal = (object, propName, searched=[]) => {
searched.push( object)
for (let key in object) {
if (key === propName) {
return object[key]
}
else {
let obj = object[ key]
if( obj && (typeof obj == "object" || typeof obj == "function")) {
if( searched.indexOf(obj) >=0) {
continue
}
let found = util.findVal(obj, propName, searched)
if( found != searched) {
return found
}
}
}
}
searched.pop();
// not in object:
return searched.length ? searched : undefined
}
I ended up writing this function.
It is a refactor of a function found here: Recursively looping through an object to build a property list
added a depth parameter to avoid stack overflow in chrome devtools.
function iterate(obj, context, search, depth) {
for (var property in obj) {
if (Object.prototype.hasOwnProperty.call(obj, property)) {
if(typeof obj[property] == 'function') continue;
if( property == search ){
console.log(context+property);
return;
}
if (typeof obj[property] == "object" && depth < 7) {
//console.log('--- going in: ' + context+property);
iterate(obj[property], context+property+'.', search, depth+1);
}
/*else {
console.log(context+property);
}*/
}
}
}
Returns the value of the field with the specified name.
data is the root node/object.
keyName is a string name of the field/member.
If keyName specifies a field that is itself an object, then that object is returned.
function find (data, keyName) {
for (const key in data) {
const entry = data[key]
if (key === keyName)
return entry
if (typeof entry === 'object') {
const found = find(entry, keyName)
if (found)
return found
}
}
}
The for loop goes through each field and if that field is an object then it will recurse into that object.
Here is a piece of code which find the key you are looking for in your rootObj tree. And add it to the root object. So by the end you will have access to you key like this rootObj[key].
findKeyVal(object, key, rootObj) {
if(object instanceof Object) {
let keys = Object.keys(object);
if(keys.includes(key) && !isNullOrUndefined(object[key])) {
rootObj[key] = object[key];
return;
}
else {
keys.filter(k => object[k] instanceof Object).forEach( k => {
this.findKeyVal(object[k], key, rootObj);
})
}
}
}
Old question, but to check if the property exists anywhere in the hierarchy of an object, try this simple option
var obj = {
firstOperand: {
firstOperand: {
firstOperand: {
sweptArea: 5
}
}
}
};
function doesPropertyExists ( inputObj, prop )
{
return JSON.stringify(obj).indexOf( "\""+ prop +"\":" ) != -1;
};
console.log( doesPropertyExists( obj, "sweptArea" ) );
console.log( doesPropertyExists( obj, "firstOperand" ) );
console.log( doesPropertyExists( obj, "firstOperand22" ) );

Search recursively for value in object by property name

I'm building an utility function that should search for a property name and return its value once it is found. It should do this recursively:
// Function
util.findVal = (object, propName) => {
for (let key in object) {
if (key === propName) {
console.log(propName)
console.log(object[key])
return object[key]
} else {
util.findVal(object[key], propName)
}
}
}
// Input
object: {
photo: {
progress: 20
}
}
// Usage
util.findVal(object, 'progress')
However the console log goes forever and the browser crashes. What am I doing wrong?
EDIT:
This is how I'm calling the function:
// Input
item: {
photo: {
file: {},
progress: 20
}
}
this.findProgress(item)
methods: {
findProgress (item) {
return util.findVal(item, this.propName)
}
}
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'));
Your code has a few errors:
You're recursively calling util.findVal but not returning the result of the call. Code should be return util.findVal(...)
You're not passing the attribute name key to the recursive call
You're not handling the possibility of a reference loop
If an object contains a key and also a sub-object that contains the key which value is returned is random (depends on the sequence in which the keys are analyzed)
The third problem is what can cause infinite recursion, for example:
var obj1 = {}, obj2 = {};
obj1.x = obj2; obj2.y = obj1;
if you just keep looking recursively searching in obj1 or obj2 could lead to infinite recursion.
Unfortunately for reasons not clear to me in Javascript is impossible to know the object "identity"... (what Python id(x) does) you can only compare an object to another. This means that to know if an object has already been seen in the past you need a linear scan with known objects.
ES6 added the possibility to check object identity with Set and Map where objects can be used as keys. This allows for faster (sub-linear) search times.
A search solution that runs in depth order could be for example:
function findVal(obj, key) {
var seen = new Set, active = [obj];
while (active.length) {
var new_active = [], found = [];
for (var i=0; i<active.length; i++) {
Object.keys(active[i]).forEach(function(k){
var x = active[i][k];
if (k === key) {
found.push(x);
} else if (x && typeof x === "object" &&
!seen.has(x)) {
seen.add(x);
new_active.push(x);
}
});
}
if (found.length) return found;
active = new_active;
}
return null;
}
given an object and an attribute name, returns all the values found with that name at the first depth they are found (there can be more than one value: for example when searching {x:{z:1}, y:{z:2}} for the key "z" two values are at the same depth).
The function also correctly handles self-referencing structures avoiding infinite search.
Don't write your own utility if you can avoid it.
Use something like jsonpath
Some examples of supported syntax:
JSONPath Description
$.store.book[*].author The authors of all books in the store
$..author All authors
$.store.* All things in store, which are some books and a red bicycle
$.store..price The price of everything in the store
$..book[2] The third book
$..book[(#.length-1)] The last book via script subscript
$..book[-1:] The last book via slice
$..book[0,1] The first two books via subscript union
$..book[:2] The first two books via subscript array slice
$..book[?(#.isbn)] Filter all books with isbn number
try changing else statement like this
return util.findVal(object[key],propName)
I know this is an old post, but I found it helpful to answer a problem I had with recursively finding a value by it's key. I further developed the answer given by Nina Scholz, and came up with the following. It should be quicker as it is not creating an array of all of the keys each time it is recursively invoked. Also, this will explicitly return false if the key is not found.
function findVal(obj, keyToFind) {
if (obj[keyToFind]) return obj[keyToFind];
for (let key in obj) {
if (typeof obj[key] === 'object') {
const value = findVal(obj[key], keyToFind);
if (value) return value;
}
}
return false;
}
var object = { photo: { progress: 20 }};
console.log(findVal(object, 'progress'));
I think you are saying that you want to look for the property name anywhere recursively within the objects tree of properties and sub-properties. If so, here is how I would approach this:
var object1 = _getInstance(); // somehow we get an object
var pname = 'PropNameA';
var findPropertyAnywhere = function (obj, name) {
var value = obj[name];
if (typeof value != 'undefined') {
return value;
}
foreach(var key in obj) {
var v2 = findPropertyAnywhere(obj[key], name);
if (typeof v2 != 'undefined') {
return v2;
}
}
return null;
}
findPropertyAnywhere(object1, pname);
Think about it if there is no key found.
I think you could do something like this instead of search
return object[propName] || null
In your code there was a breakpoint missing, I guess you are trying to search inside the whole object not just the directly related attributes so here is an edit for you code
EDIT:
util.findVal = (object, propName) =>{
if(!!object[propName]){
return object[propName]
}else{
for (let key in object) {
if(typeof object[key]=="object"){
return util.findVal(object[key], propName)
}else{
return null
}
}
}
}
Found this question in the realm of needing a general solution to check if an object contains a specific value anywhere in its hierarchy (regardless of the key), which can include arrays of course. So the following does not answer OPs question directly or improve upon other solutions but it might help others looking for the same thing I did and finding this post:
function hasValue(object, value) {
return Object.values(object).some(function(val) {
if (val === value) {
return true;
}
if (val && typeof val === 'object') {
return hasValue(val, value);
}
if (val && val.isArray()) {
return val.some((obj) => {
return hasValue(obj, value);
})
}
});
}
it is of course inspired by #Nina Scholz 's solution!
An answer depends a on how complex you want to get. For example a JSON parsed array doesn't contain functions - and I'm fairly certain it won't contain property value set to a parent node in object tree.
This version returns the property value of the first property name found whilst searching the object tree. undefined is returned if either the named property was not found or has a value of undefined. Some modifications would be needed to tell the difference. It does not re-search parent nodes already being searched, nor try to scan null objects!
let util = {};
util.findVal = (object, propName, searched=[]) => {
searched.push( object)
for (let key in object) {
if (key === propName) {
return object[key]
}
else {
let obj = object[ key]
if( obj && (typeof obj == "object" || typeof obj == "function")) {
if( searched.indexOf(obj) >=0) {
continue
}
let found = util.findVal(obj, propName, searched)
if( found != searched) {
return found
}
}
}
}
searched.pop();
// not in object:
return searched.length ? searched : undefined
}
I ended up writing this function.
It is a refactor of a function found here: Recursively looping through an object to build a property list
added a depth parameter to avoid stack overflow in chrome devtools.
function iterate(obj, context, search, depth) {
for (var property in obj) {
if (Object.prototype.hasOwnProperty.call(obj, property)) {
if(typeof obj[property] == 'function') continue;
if( property == search ){
console.log(context+property);
return;
}
if (typeof obj[property] == "object" && depth < 7) {
//console.log('--- going in: ' + context+property);
iterate(obj[property], context+property+'.', search, depth+1);
}
/*else {
console.log(context+property);
}*/
}
}
}
Returns the value of the field with the specified name.
data is the root node/object.
keyName is a string name of the field/member.
If keyName specifies a field that is itself an object, then that object is returned.
function find (data, keyName) {
for (const key in data) {
const entry = data[key]
if (key === keyName)
return entry
if (typeof entry === 'object') {
const found = find(entry, keyName)
if (found)
return found
}
}
}
The for loop goes through each field and if that field is an object then it will recurse into that object.
Here is a piece of code which find the key you are looking for in your rootObj tree. And add it to the root object. So by the end you will have access to you key like this rootObj[key].
findKeyVal(object, key, rootObj) {
if(object instanceof Object) {
let keys = Object.keys(object);
if(keys.includes(key) && !isNullOrUndefined(object[key])) {
rootObj[key] = object[key];
return;
}
else {
keys.filter(k => object[k] instanceof Object).forEach( k => {
this.findKeyVal(object[k], key, rootObj);
})
}
}
}
Old question, but to check if the property exists anywhere in the hierarchy of an object, try this simple option
var obj = {
firstOperand: {
firstOperand: {
firstOperand: {
sweptArea: 5
}
}
}
};
function doesPropertyExists ( inputObj, prop )
{
return JSON.stringify(obj).indexOf( "\""+ prop +"\":" ) != -1;
};
console.log( doesPropertyExists( obj, "sweptArea" ) );
console.log( doesPropertyExists( obj, "firstOperand" ) );
console.log( doesPropertyExists( obj, "firstOperand22" ) );

Find and retrive object value by key, include nested objects

I am trying to find a value by key without knowing the object, include nested object, so the function will get a key and a object and return the value or undefined.
This is my function:
/* Iterate over object and include sub objects */
function iterate (obj, key) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
//in case it is an object
if (typeof obj[property] == "object") {
if (obj.hasOwnProperty(key)) {
return obj[key]; //return the value
}
}
else {
iterate(obj[property]);
}
}
}
return undefined;
}
I call return inside a loop so it will be more efficient(hope so...).
1.is anyone have this function ready? this one does not work.
2.someone knows what to change to make it work?
Any help, including angular.js functions will be great.
Thanks.
You reversed things a bit and you forgot to pass the second parameter to the recursive function call. Also, in this case there's no need to return undefined, because that is the default.
function iterate (obj, key) {
var result;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
// in case it is an object
if (typeof obj[property] === "object") {
result = iterate(obj[property], key);
if (typeof result !== "undefined") {
return result;
}
}
else if (property === key) {
return obj[key]; // returns the value
}
}
}
}
EDIT: Actually, we should check if the property is equal to the key BEFORE checking if the value is an iterable object, in the case where we are looking for a key whose value is an object. Thanks to #Catinodeh!
function iterate (obj, key) {
var result;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (property === key) {
return obj[key]; // returns the value
}
else if (typeof obj[property] === "object") {
// in case it is an object
result = iterate(obj[property], key);
if (typeof result !== "undefined") {
return result;
}
}
}
}
}
Unflatten it first with the function that solved this problem:
Fastest way to flatten / un-flatten nested JSON objects
and then simply use hasOwnProperty again
Here is a code snippet that worked for me. The assumption for me I was only searching nested objects, with no arrays.
function searcObject(obj, key){
var found = false
if(typeof obj == 'object' && obj !== null){
Object.keys(obj).forEach(function(prop) {
if(prop == key){
value = obj[key];
return true;
} else{
searcObject(obj[prop], key);
}
});
} else {
return false;
};
};

Categories

Resources