Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

Javascript list loop/recursion to create an object

I'm trying to create a function to process a list of numbers relating to depth using recursion or loops in JavaScript.

The following "input" needs to be processed into the "output", and it needs to work for arbitary lists.

One thing to note is that numbers increase by either 0 or 1 but may decrease by any amount.

var input = [0, 1, 2, 3, 1, 2, 0]

var output =
  [ { number: 0, children: 
      [ { number: 1, children: 
          [ { number: 2, children: 
              [ { number: 3, children: [] } ]
            } 
          ] 
        } 
      , { number: 1, children: 
          [ { number: 2, children: [] } ]
        } 
      ] 
    } 
  , { number: 0, children: [] } 
  ] 

I worked it out myself, although it needs some refinement.

var example = [0, 1, 2, 2, 3, 1, 2, 0]
var tokens = []
var last = 0
const createJSON = (input, output) => {
  if (input[0] === last) {
    output.push({ num: input[0], children: [] })
    createJSON(input.splice(1), output)
  } 
  else if (input[0] > last) {
    last = input[0]
    output.push(createJSON(input, output[output.length-1].children))
  } 
  else if (input[0] < last) {
    var steps = input[0]
    var tmp = tokens
    while (steps > 0) {
      tmp = tmp[tmp.length-1].children
      steps--
    }
    tmp.push({ num: input[0], children: [] })
    createJSON(input.splice(1), tmp)
  }
}
createJSON(example, tokens)
console.log(tokens)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In fact, it's a very simple problem to solve...

var input   = [0, 1, 2, 3, 1, 2, 0]
  , output  = []
  , parents = [output]
  ;
for(el of input)
  {
  let nv = { number:el, children:[] }
  parents[el].push( nv )
  parents[++el] = nv.children  // save the  @ddress of children:[] for adding items on
  }
console.log( output )
.as-console-wrapper { max-height: 100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...