Flatten object to array?

前端 未结 7 1256
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 03:21

I\'m using an object as a hash table. I\'d like to quickly print out its contents (for alert() for instance). Is there anything built in to convert a hash into

7条回答
  •  温柔的废话
    2021-01-05 03:45

    Here is my version of it. It should allow you to flatten input like below:

    var input = {
       a: 'asdf',
       b: [1,2,3],
       c: [[1,2],[3,4]],
       d: {subA: [1,2]}
    }
    

    The function is like this:

        function flatten (input, output) {
    
          if (isArray(input)) {
            for(var index = 0, length = input.length; index < length; index++){
              flatten(input[index], output);
            }
          }
          else if (isObject(input)) {
            for(var item in input){
              if(input.hasOwnProperty(item)){
                flatten(input[item], output);
              }
            }
          }
          else {
            return output.push(input);
          }
        };
    
        function isArray(obj) {
          return Array.isArray(obj) || obj.toString() === '[object Array]';
        }
    
        function isObject(obj) {
          return obj === Object(obj);
        }
    

    Usage is something like:

    var output = []

    flatten(input, output);

    Then output should be the flattened array.

提交回复
热议问题