find and modify deeply nested object in javascript array

前端 未结 6 1880
情深已故
情深已故 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:59

    I wrote this code recently to do exactly this, as my backend is rails and wants keys like:

    first_name
    

    and my front end is react, so keys are like:

    firstName
    

    And these keys are almost always deeply nested:

    user: {
      firstName: "Bob",
      lastName: "Smith",
      email: "bob@email.com"
    }
    

    Becomes:

    user: {
      first_name: "Bob",
      last_name: "Smith",
      email: "bob@email.com"
    }
    

    Here is the code

    function snakeCase(camelCase) {
      return camelCase.replace(/([A-Z])/g, "_$1").toLowerCase()
    }
    
    export function snakeCasedObj(obj) {
      return Object.keys(obj).reduce(
        (acc, key) => ({
          ...acc,
          [snakeCase(key)]: typeof obj[key] === "object" ? snakeCasedObj(obj[key]) : obj[key],
        }), {},
      );
    }
    

    Feel free to change the transform to whatever makes sense for you!

提交回复
热议问题