Best way to flatten JS object (keys and values) to a single depth array

前端 未结 10 958
梦毁少年i
梦毁少年i 2020-12-05 05:10

I have written this small function to get all keys and values of an object and store them into an array. The object might contain arrays as values...

Object {

10条回答
  •  被撕碎了的回忆
    2020-12-05 05:30

    Generate an array of tuples (two-element arrays) of keys and values (which might themselves be arrays), then deep-flatten it.

    function flattenObject(obj) { 
          return flatten(Object.keys(obj).map(k => [toNumber(k), obj[k]]));
    }
    
    // Substitute your own favorite flattening algorithm.
    const flatten = a => Array.isArray(a) ? [].concat(...a.map(flatten)) : a;
    
    // Convert to number, if you can.
    const toNumber = n => isNaN(+n) ? n : +n;
    
    console.log(flattenObject({a: [1, 2], b: 3, 0: [1, 2, 3, 4, 5]}));

提交回复
热议问题