Iterate through Nested JavaScript Objects

2019-01-04 11:34发布

I'm trying to iterate through a nested object to retrieve a specific object identified by a string. In the sample object below, the identifier string is the "label" property. I can't wrap my head around how to iterate down through the tree to return the appropriate object. Any help or suggestions would be greatly appreciated.

var cars = 
    {
        label: 'Autos',
        subs:
            [
                {
                    label: 'SUVs',
                    subs: []
                },
                {
                    label: 'Trucks',
                    subs: [
                              {
                                label: '2 Wheel Drive',
                                subs: []
                              },
                              {
                                label: '4 Wheel Drive',
                                subs: [
                                          {
                                            label: 'Ford',                                        
                                            subs: []
                                          },
                                          {
                                            label: 'Chevrolet',
                                            subs: []                                      
                                          }
                                      ]                          
                              }
                          ]    
                },
                {
                    label: 'Sedan',
                    subs: []
                }
            ]
    }

8条回答
▲ chillily
2楼-- · 2019-01-04 11:55

modify from Peter Olson's answer: https://stackoverflow.com/a/8085118

  1. can avoid string value !obj || (typeof obj === 'string'
  2. can custom your key

var findObjectByKeyVal= function (obj, key, val) {
  if (!obj || (typeof obj === 'string')) {
    return null
  }
  if (obj[key] === val) {
    return obj
  }

  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      var found = findObjectByKeyVal(obj[i], key, val)
      if (found) {
        return found
      }
    }
  }
  return null
}
查看更多
Lonely孤独者°
3楼-- · 2019-01-04 12:01

I made a pick method like lodash pick. It is not exactly good like lodash _.pick, but you can pick any property event any nested property.

  • You just have to pass your object as a first argument then an array of properties in which you want to get their value as a second argument.

for example:

let car = { name: 'BMW', meta: { model: 2018, color: 'white'};
pick(car,['name','model']) // Output will be {name: 'BMW', model: 2018}

Code :

const pick = (object, props) => {
  let newObject = {};
  if (isObjectEmpty(object)) return {}; // Object.keys(object).length <= 0;

  for (let i = 0; i < props.length; i++) {
    Object.keys(object).forEach(key => {
      if (key === props[i] && object.hasOwnProperty(props[i])) {
        newObject[key] = object[key];
      } else if (typeof object[key] === "object") {
        Object.assign(newObject, pick(object[key], [props[i]]));
      }
    });
  }
  return newObject;
};

function isObjectEmpty(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) return false;
  }
  return true;
}
export default pick;

and here is the link to live example with unit tests

查看更多
登录 后发表回答