Given the following three objects, what is an efficient way to return the first object that contains a key-value pair?
var obj = {
item1: {
name: 'apple',
color: 'red'
},
item2: {
name: 'blueberry',
color: 'blue'
},
item3: {
name: 'cherry',
color: 'red'
}
};
var obj2 = {
collection: [
{
item1: {
name: 'apple',
color: 'red'
},
item2: {
name: 'blueberry',
color: 'blue'
},
item3: {
name: 'cherry',
color: 'red'
}
}
]
};
var obj3 = {
items: [
{
item1: {
name: 'apple',
color: 'red'
}
},
{
item2: {
name: 'blueberry',
color: 'blue'
},
},
{
item3: {
name: 'cherry',
color: 'red'
}
}
]
};
I would like to get the same results for the following three statements:
getObject(obj, 'color', 'red');
getObject(obj2, 'color', 'red');
getObject(obj3, 'color', 'red');
Output:
{
name: 'apple',
color: 'red'
}
Here's what I have so far, but I think it's missing a closure somewhere since it breaks when the function calls itself:
function getObject(arg, key, val) {
if (typeof arg!=='object') return null;
switch (Object.prototype.toString.call(arg)) {
case '[object Array]':
for (var i=0; i<arg.length; ++i) {
getObject(arg[i], key, val);
}
break;
case '[object Object]':
for (var i in arg) {
if (arg.hasOwnProperty(i)) {
if (typeof arg[i]==='object') {
getObject(arg[i], key, val);
} else {
if (i===key && arg[i]===val) {
return arg;
}
}
}
}
break;
}
}