Lodash remove items recursively

前端 未结 6 732
难免孤独
难免孤独 2020-12-03 22:35

Given this JSON object, how does lodash remove the reach value from the objects?

{ 
    total: 350,
    SN1: { 
        reach: 200,
        enga         


        
6条回答
  •  执笔经年
    2020-12-03 22:57

    Recursively omit keys from an object by defining an array of exclude keys in ES6 + Typescript.

    omitDeep(myObject, [omitKey1, omitKey2, ...omitKeyN])

    // omitDeep.ts
    
    /**
     * Recursively remove keys from an object
     * @usage
     *
     * const input = {
     *   id: 1,
     *   __typename: '123',
     *   createdAt: '1020209',
     *   address: {
     *     id: 1,
     *     __typename: '123',
     *   },
     *   variants: [
     *     20,
     *     {
     *       id: 22,
     *       title: 'hello world',
     *       __typename: '123',
     *       createdAt: '1020209',
     *       variantOption: {
     *         id: 1,
     *         __typename: '123',
     *       },
     *     },
     *     {
     *       id: 32,
     *       __typename: '123',
     *       createdAt: '1020209',
     *     },
     *   ],
     * }
     *
     * const output = {
     *   id: 1,
     *   address: {
     *     id: 1,
     *   },
     *   variants: [
     *     20,
     *     {
     *       id: 22,
     *       title: 'hello world',
     *       variantOption: {
     *         id: 1,
     *       },
     *     },
     *     {
     *       id: 32,
     *     },
     *   ],
     * }
     *
     * expect(omitDeep(input, ['createdAt, 'updatedAt', __typename']).to.deep.equal(output) // true
     *
     * @param {object} input
     * @param {Array>} excludes
     * @return {object}
     */
    const omitDeep = (input: object, excludes: Array): object => {
      return Object.entries(input).reduce((nextInput, [key, value]) => {
        const shouldExclude = excludes.includes(key)
        if (shouldExclude) return nextInput
    
        if (Array.isArray(value)) {
          const arrValue = value
          const nextValue = arrValue.map((arrItem) => {
            if (typeof arrItem === 'object') {
              return omitDeep(arrItem, excludes)
            }
            return arrItem
          })
          nextInput[key] = nextValue
          return nextInput
        } else if (typeof value === 'object') {
          nextInput[key] = omitDeep(value, excludes)
          return nextInput
        }
    
        nextInput[key] = value
    
        return nextInput
      }, {})
    }
    
    export default omitDeep
    

提交回复
热议问题