Article From:https://segmentfault.com/q/1010000011701184
Question:

There are simple objects.

numbers:{
    one:'one',
    two:'two',
    three:'htree',
    fourth:'fourth'
}

I want to turn to the following code by judging the existing form.

if(numbers.fourth){
    let num = {
        [fourth]:{
            [three]:{
                [two]:{
                    [one]:'ok'
                }
            }
        }
    }
}else if(numbers.three){
    let num = {
        [three]:{
            [two]:{
                [one]:'ok'
            }
        }
    }
}else if(numbers.two){
    ...
    Here is not the same parameter.}

numbersThe attributes in the object are changeable, so it is necessary to dynamically determine and generate the corresponding structure of the object, how to achieve a good point (minimize the amount of code)?
Ask everyone to pass by the great God, and enthusiastically eat the melon crowd!!!

Answer 0:

Variable number of attributes
The following code is as follows:

var numbers = {
  one: 'one',
  two: 'two',
  three: 'three',
  fourth: 'fourth'
}

function structuring(arr) {
  var keys = ['fourth', 'three', 'two', 'one']
  var rtn = {}
  keys.forEach((key, index) => {
    if (arr[key] && !Object.keys(rtn).length) {
      for (var i = keys.length - 1; i >= index; i--) {
        var rtnKey = '[' + keys[i] + ']'
        if (i === keys.length - 1) {
          rtn[rtnKey] = 'OK'
        } else {
          var tmp = {}
          tmp[rtnKey] = rtn
          rtn = tmp
        }
      }
    }
  })
  return rtn
}

console.log(structuring(numbers))

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *