Flatten an object using lodash

前端 未结 3 558
花落未央
花落未央 2021-01-26 04:48

I have below this nested object

I need to create an array using this object containing keys. And if keys are object then it should use .d

3条回答
  •  情话喂你
    2021-01-26 05:24

    inspired by the answer given in this post and understanding you just want to get the property-names, not values, you could do it like this. sorry, this uses plain javascript.

    function flattenObjectToKeyArray(ob) {
      var toReturn = [];
      for (var prop in ob) {
        if (!ob.hasOwnProperty(prop)) continue;
    
        if ((typeof ob[prop]) == 'object' && ob[prop] !== null) {
          var flatObject = flattenObjectToKeyArray(ob[prop]);
          for (var idx = 0; idx < flatObject.length; idx++) {
            toReturn.push(prop + '.' + flatObject[idx]);
          }
        } else {
          toReturn.push(prop);
        }
      }
      return toReturn;
    }
    

提交回复
热议问题