Flatten object to array?

前端 未结 7 1272
佛祖请我去吃肉
佛祖请我去吃肉 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:43

    Maybe a little late, but here you have my version of the answer, updated to ES2015. I use a recursive function and it works even if there are other objects inside the main object:

    function objectFlattener (object) {
      return Reflect.apply(Array.prototype.concat, [], Object.keys(object).map(key => {
        if (object[key] instanceof Object) {
          return objectFlattener(object[key]);
        }
        return `${ key }: ${ object[key] }`;
      }));
    }
    

    So changing the last return you can format the element inside your array.

提交回复
热议问题