How can I handle complex nested data transformations in TypeScript using lodash?

I’m working on a TypeScript project where I need to perform complex transformations on deeply nested JSON data. I’m using lodash for utility functions, but I’m struggling with the following scenario:

{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "details": {
        "age": 25,
        "address": {
          "city": "Wonderland",
          "postalCode": "12345"
        }
      }
    },
    {
      "id": 2,
      "name": "Bob",
      "details": {
        "age": 30,
        "address": {
          "city": "Builderland",
          "postalCode": "67890"
        }
      }
    }
  ]
}

I need to:

  • Flatten the structure so that each user’s data is a single object with properties including the user’s address in a flattened format.
  • Transform the data into a new structure where the user’s postalCode is used as the key and the value is an object containing name, age, and city.

Questions:

  • Are there more efficient ways to flatten and transform this data using lodash?

  • How can I improve the readability and maintainability of this code, especially if the data structure becomes more complex?

Here’s what I’ve tried:

import _ from 'lodash'; 

const nestedData = {
  users: [
    {
      id: 1,
      name: "Alice",
      details: {
        age: 25,
        address: {
          city: "Wonderland",
          postalCode: "12345"
        }
      }
    },
    {
      id: 2,
      name: "Bob",
      details: {
        age: 30,
        address: {
          city: "Builderland",
          postalCode: "67890"
        }
      }
    }
  ]
};

// Flattening data
const flattenedData = _.flatMap(nestedData.users, user => ({
  id: user.id,
  name: user.name,
  age: user.details.age,
  city: user.details.address.city,
  postalCode: user.details.address.postalCode
}));

console.log('Flattened Data:', flattenedData);

// Transforming data
const transformedData = _.mapValues(
  _.keyBy(flattenedData, 'postalCode'),
  ({ name, age, city }) => ({ name, age, city })
);

console.log('Transformed Data:', transformedData);