How to enumerate complex javascript object

对着背影说爱祢 提交于 2019-12-24 20:19:16

问题


How to enumerate complex javascript object to get property paths to plain values?

In example if object is:

let complex = {
  person: {name: 'mat', age: 31},
  car: {
      model: 'Volsan',
      engine: 'large', 
      doors:[
        { side:'right front', color: 'blue' },
        { side:'left rear', color: 'red' }
      ]
   }
};

and outcome would be like:

complex.person.name
complex.person.age
complex.car.model
complex.car.engine
complex.car.doors[0].side
complex.car.doors[0].color
complex.car.doors[1].side
complex.car.doors[1].color

so that there would be only those values that are "ending the graph"

eg. it would be reverse _.at from lodash: https://lodash.com/docs/4.17.5#at


回答1:


This recursive solution uses Array.map(), and Object.keys() to add the keys to a base path. Then we flatten the resulting array using Array.concat() and spread:

const complex = {
  person: {name: 'mat', age: 31},
  car: {
      model: 'Volsan',
      engine: 'large', 
      doors:[
        { side:'right front', color: 'blue' },
        { side:'left rear', color: 'red' }
      ]
   }
}

const addDot = (b, s) => `${b}${b && '.'}${s}`
const wrapBrackets = (b, s) => `${b}[${s}]`

const mapPaths = (obj, base = '') => {
  if(typeof obj !== 'object') {
    return base;
  }

  const formatter = Array.isArray(obj) ? wrapBrackets : addDot;

  return [].concat(...Object.keys(obj)
    .map((key) => mapPaths(obj[key], formatter(base, key))))
};

const result = mapPaths(complex)

console.log(result);


来源:https://stackoverflow.com/questions/49125398/how-to-enumerate-complex-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!