0

How to get all the values of the object and compare

Object :

obj = {
     a : 10,
     b : [{b1 : 101 , b2:201},{b3 : 102 , b4:204}],
     c : [{c1 : 107 , c2:209 ,d :[{d1:109},{d2:402}]}]
}

function compareValues(101,obj) {           

   if (retriveValueFromObject(obj,101)) {
       return true;
   } else {
      return false;
   } 

   function comparator(a, b) {
       return ('' + a).toLowerCase().indexOf(('' + b).toLowerCase()) > -1;
   }
}

Pending : retriveValueFromObject() need to be implemented such a way that i will loop in to all the key value pair of the object and send back flag(t/f) if value is in the object.

Preview
  • 35,317
  • 10
  • 92
  • 112
praveenpds
  • 2,936
  • 5
  • 26
  • 43

3 Answers3

1

You could try something like this:

function retriveValueFromObject(theObject, value) {
  for(var prop in theObject) {
      if(theObject[prop] == value) {
        return true;
      }
      if(theObject[prop] instanceof Object || theObject[prop] instanceof Array)
       return getObject(theObject[prop]);
  }
  return false;
}

I found this here : https://stackoverflow.com/a/15524326/1062711

Community
  • 1
  • 1
ex0ns
  • 1,116
  • 8
  • 19
0

try:

function retrieveValueFromObject(obj,101) {
    var result;
    for (var key in obj){
        if (typeof(obj[key]) !== 'Object')
            result = comperator(101, obj[key]);
        else
            result = retrieveValueFromObject(obj[key],101);
    }
    return result;
}

didn't get to test it myself, though.

user3154108
  • 1,264
  • 13
  • 23
0

I would suggest to retrieve all values from object recursively into array and then check with Array.prototype.indexOf():

function getValues(obj) {
    var result = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            var curVal = obj[key];
            if (typeof (curVal) === 'object') {
                result = result.concat(getValues(curVal));
            } else {
                result.push(curVal);
            }
        }
    }
    return result;
}
console.log(getValues(o));
console.log(getValues(o).indexOf(101) !== -1);
console.log(getValues(o).indexOf('nosuchvalue') !== -1);

Fiddle

Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57