0

I have a nested object which looks like this :

let obj = {
_id:{}
person:{
    $search:{fname:true}
    _id:{},
    fname:{}
},
code:{},
vnvEmpName:{}

}

I have to search for a $search keyword in this and get the key which is inside it that is fname in this case, it can contain multiple keys as well and I have to retrieve all of it.

I tried something like this :

function findById(obj, id) {                             

var result;
for (var p in obj) {
    if (obj.id === id) {
        return obj;
    } else {
        if (typeof obj[p] === 'object') {
            result = findById(obj[p], id);
            if (result) {
                return result;
            }
        }
    }
}
return result;

}

If the object is in this way :

let obj = {
_id: {},
person: {
    $search: {
        lname: true
    },
    _id: {},
    fname: {},
    something:{
        $search: {
            fname: true
        },
    }
},
code: {},
$search: {
    mname: true
},
vnvEmpName: {}

} I want to retrieve all the attributes inside the $search of every block.

but I don't know how to get the keys inside a particular key as I am so new to the javascript.

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
ra_pri
  • 117
  • 1
  • 3
  • 16
  • Possible duplicate of [Iterate through Nested JavaScript Objects](https://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objects) – SirPeople May 17 '18 at 08:33
  • @SirPeople The attribute is not at the upper level like in the other problem. – ra_pri May 17 '18 at 08:50
  • The domain is a bit different but the solution is totally related. You want to go through the keys and extract those objects under the key $search, then just do Object.keys(extractedObject) so you get all the keys under $search – SirPeople May 17 '18 at 12:57

3 Answers3

0

To just get the keys you can simply do it using Object.keys(yourObject) MDN Object.keys

You can also use lodash to obtain the same result

hyprstack
  • 3,137
  • 2
  • 36
  • 70
0

Need to recursively search through the object

let obj = {
  _id: {},
  person: {
    $search: {
      fname: true
    },
    _id: {},
    fname: {}
  },
  code: {},
  vnvEmpName: {}
}

function findById(obj, id) {
  var result = "";
  // iterate the object using for..in
  for (var keys in obj) {
    // check if the object has any property by that name 
    if (obj.hasOwnProperty(keys) && typeof obj[keys] === 'object') {
      // if the key is not undefined get it's value
      if (obj[keys][id] !== undefined) {
        result = (obj[keys][id])
      } else {
        // else again call the same function using the new obj value
        findById(obj[keys], id)
      }
    }

  }
  return result;
}
console.log(findById(obj, 'fname'))
brk
  • 43,022
  • 4
  • 37
  • 61
  • Thanks @brk it worked, but the thing is it's returning only the first $search attribute, I want to retrieve it even if other entries are also having $search. – ra_pri May 17 '18 at 10:05
0

You can use the following function:

const objectifier = function (splits, create, context) {
    let result = context;

    for (let i = 0, key; result && (key = splits[i]); i += 1) {
      if (key in result) { result = result[key]; } else {
        result = create
          ? result[key] = {}
          : undefined;
      }
    }

    return result;
  };

Have a look at the example below:

let obj = {
    '_id': {aa: 'aa'},
    'person': {
        '$search': {
            'fname': true
        },
        '_id': {'bb': 'bb'},
        'fname': {'cc': 'cc'}
    },
    'code': {'dd': 'dd'},
    'vnvEmpName': {'name': 'sdsdd'}
}


const objectifier = function (splits, create, context) {
    let result = context;

    for (let i = 0, key; result && (key = splits[i]); i += 1) {
      if (key in result) { result = result[key]; } else {
        result = create
          ? result[key] = {}
          : undefined;
      }
    }

    return result;
  };

console.log(objectifier('person.$search'.split('.'), false, obj));

// { fname: true }
Neeraj Wadhwa
  • 525
  • 2
  • 6
  • 18
  • It will not be always 'person.$search', it could change as $search can occur multiple times for different entries. – ra_pri May 17 '18 at 10:07
  • You need to provide the path to that key and you'll get the value. Try it against your requirements. – Neeraj Wadhwa May 17 '18 at 10:27