【一起来做题】001.将一个深层次对象,构造成左边是路径,右边是最终的value值

题目

// Given an object, then convert it to a new object structure
// For example:
const entry = {
  a: {
    b: {
      c: {
        dd: 'abcdd',
      },
    },
    d: {
      xx: 'adxx',
    },
    e: 'ae',
  },
  f: 'f'
};
// When we invoke the "convertObject" method and pass the parameter "entry" object: convertObject(entry)
// The result is:
// {
//   'a.b.c.dd': 'abcdd',
//   'a.d.xx': 'adxx',
//   'a.e': 'ae',
//   'f': 'f'
// };
// Please complete the convertObject method

一种解题思路

function convertObject(o) {
  var arr1 = [];
  var arr2 = [];
  var obj = {};
  arr1.push(o);
  while (arr1.length) {
    const cur = arr1.pop();
    Object.keys(cur).map((item, index) =>{
    if(Object.prototype.toString.call(cur[item]) === '[object String]') {
      obj[item]= cur[item]
    } else {
      Object.keys(cur[item]).map((item2, index2) => {
        cur[item][item+'.'+item2] = cur[item][item2];
        delete cur[item][item2];
      })
      arr1.push(cur[item]);
    }
  })
  }
  return obj;
}


console.log(convertObject(entry));

其他解题思路欢迎大家留言一起探讨哦

你可能感兴趣的:(JavaScript,javascript)