var OBJ = {
code: 42,
item1: [{
id: 1,
name: 'foo'
}, {
id: 2,
city: 'NY'
name: 'bar'
}],
thing: [{
id: 14,
name: 'foo'
}, {
id: 5,
street: 'E43'
name: 'pub'
}]
};
Javascript object(OBJ) I need a method that returns VALUE of KEY I pass as an argument if KEY is not present in OBJ method should return undefined
getKeyValueFromObject(OBJ , 'street') // should return 'E43'
getKeyValueFromObject(OBJ , 'dog') // should return undefined
I tried this(not working)
getKeyValueFromObject(obj: any, search: string) {
const notFound = {};
Object.keys(obj).forEach(key => {
if (key !== null && key !== undefined && !(obj[key] === undefined || obj[key] === null)) {
if (key === search) {
return obj[key];
} else if (obj[key].constructor === {}.constructor) {
const result = this.getKeyValueFromObject(obj[key], search);
if (result !== notFound) return result;
} else if (Array.isArray(obj[key])) {
obj[key].forEach(element => {
const result = this.getKeyValueFromObject(element, search);
if (result !== notFound) return result;
});
}
}
});
return {};
}