Skip to content Skip to sidebar Skip to footer

Save Data In A Specific Way

I have an application where user have to input data about it and after saving that form, the data should be outputed in a certain form. The expected data should look like this:

Solution 1:

First you have to destruct (doc) the form values object combining with spread operator (doc) to get the car-related values (I stored in variable carValues). After that, the only things left to do is manipulate with that variable, here I combined the use of Object.entries and Array.prototype.map

There a part with Number(key), because Object.entries() transforms object in to array of key-value pair, with key's type of string, so you have to cast it to Number first for 1-based index

constonFinish = values => {
  const { firstName, lastName, nrOfCars, ...carValues } = values
  const cars = Object.entries(carValues).map(([key, value]) => ({
    nr: Number(key) + 1,
    carsList: (value.cars || []).map((car, carIndex) => ({
      nr: carIndex + 1,
      name: car.name
    }))
  }))
  const user = {
    firstName,
    lastName,
    things: {
      cars
    }
  }
  console.log(JSON.stringify(user, null, 2))
}

Forked codesandbox for implementation

Edit polished-rain-w3cxw

Post a Comment for "Save Data In A Specific Way"