find and modify deeply nested object in javascript array

前端 未结 6 1843
情深已故
情深已故 2021-01-06 12:11

I have an array of objects that can be of any length and any depth. I need to be able to find an object by its id and then modify that object within the array. Is there an

6条回答
  •  有刺的猬
    2021-01-06 12:54

    Here's an example that extensively uses lodash. It enables you to transform a deeply nested value based on its key or its value.

    const _ = require("lodash")
    const flattenKeys = (obj, path = []) => (!_.isObject(obj) ? { [path.join('.')]: obj } : _.reduce(obj, (cum, next, key) => _.merge(cum, flattenKeys(next, [...path, key])), {}));
    
    
    const registrations = [{
      key: "123",
      responses:
      {
        category: 'first',
      },
    }]
    
    
    function jsonTransform (json, conditionFn, modifyFn) {
    
      // transform { responses: { category: 'first' } } to { 'responses.category': 'first' }
      const flattenedKeys = Object.keys(flattenKeys(json));
    
      // Easily iterate over the flat json
      for(let i = 0; i < flattenedKeys.length; i++) {
        const key = flattenedKeys[i];
        const value = _.get(json, key)
    
        // Did the condition match the one we passed?
        if(conditionFn(key, value)) {
    
          // Replace the value to the new one    
          _.set(json, key, modifyFn(key, value)) 
        }
      }
    
      return json
    }
    
    // Let's transform all 'first' values to 'FIRST'
    const modifiedCategory = jsonTransform(registrations, (key, value) => value === "first", (key, value) => value = value.toUpperCase())
    
    console.log('modifiedCategory --', modifiedCategory)
    // Outputs: modifiedCategory -- [ { key: '123', responses: { category: 'FIRST' } } ]
    

提交回复
热议问题