将嵌套对象链接列表转换为数组节点js

时间:2018-05-12 09:56:20

标签: node.js javascript-objects

链接列表嵌套对象

  

输入应该是这样的

var ii = {"val":"1","next":{"val":"2","next":{"val":"3","next":{"val":"4","next":{"val":"5","next":null}}}}}; 
  

输出应该像[1,2,3,4,5]

2 个答案:

答案 0 :(得分:4)

  

解决方案

var ii = { "val": "1", "next": { "val": "2", "next": { "val": "3", "next": { "val": "4", "next": { "val": "5", "next": null } } } } }; 
var arr = [ii.val]
while(ii.next !== null){
    ii = ii.next;
    arr.push(ii.val)
}
console.log(arr)

答案 1 :(得分:0)

演示递归函数调用的小爱好者,这可能是练习的重点并使用Array.reduce()



var ii = {
  "val":"1", "next":{
    "val":"2", "next":{
      "val":"3", "next":{
        "val":"4", "next":{ "val":"5", "next":null }
      }
    }
  }
};

const process = obj => {
  const remap = (acc,[k,v]) => ([
    ...acc,
    ...(( k === 'val') ? v : (v === null)
      ? [] : Object.entries(v).reduce(remap,[]))
  ]);

  return Object.entries(obj).reduce(remap,[]);
};

console.log(process(ii));




怀特喜欢它,效率不高。所以仍然坚持"非破坏性"你可以克隆一下这个对象并仍然递归:



var ii = {
  "val":"1", "next":{
    "val":"2", "next":{
      "val":"3", "next":{
        "val":"4", "next":{ "val":"5", "next":null }
      }
    }
  }
};


const process = obj => (({ val, next }) => 
  [ val, ...((next !== null) ? process(next): []) ])(obj);

console.log(process(ii));




更清洁,更有效,与while一样快,当然也有#34;非破坏性的"原始内容,因为它都是本地范围的。