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

前端 未结 10 972
梦毁少年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:27

    This solution can handle deeply nested objects

    const isObject = o => o && typeof o === 'object' && !(o instanceof Date);
    
    const flattenObject = obj => Object.entries(obj).reduce((acc, [key, val]) => ({
      ...acc, ...(isObject(val) ? flattenObject(val) : { [key]: val })
    }), {});
    

    Remember that this function returns an empty object for strings, dates, numbers, etc.

提交回复
热议问题