Home > Software engineering >  make it as a single object in typescript
make it as a single object in typescript

Time:03-31

I have json body as shown below

let data = [
  {country: 'India', state: 'Maharastra', population: 1000},
  {country: 'India', state: 'Karanataka', population: 800},
  {country: 'India', state: 'Kerla', population: 200},
  {country: 'India', state: 'Telangana', population: 700}
];

expected output

op = [{country: 'India', state1:1000, state2: 800, state3:200, state4: 700, Total: 2700}]

is there any way we can convert this into a single array object? is this achievable on typescript?

Thank you in advance

CodePudding user response:

const data = [
  {country: 'India', state: 'Maharastra', population: 1000},
  {country: 'India', state: 'Karanataka', population: 800},
  {country: 'India', state: 'Kerla', population: 200},
  {country: 'India', state: 'Telangana', population: 700}
];

const indexedStates = data.map((stateData, index) => 
({country: stateData.country, 
   [`state${index 1}`]: stateData.state, 
   [`population${index 1}`]: stateData.population
  })
)

const total =  data.reduce((sum, stateData) => sum   stateData.population, 0);

const finalValue = Object.assign({},...indexedStates, {total});

Playground link

CodePudding user response:

You could use reduce()

let data = [
   { country: 'India', state: 'Maharastra', population: 1000 },
   { country: 'India', state: 'Karanataka', population: 800 },
   { country: 'India', state: 'Kerla', population: 200 },
   { country: 'India', state: 'Telangana', population: 700 }
];

const result = data.reduce<{ [key: string]: any }>((acc, val, i) => {
   acc.country = val.country;
   acc[`state${i   1}`] = val.population;
   acc.total = val.population   (isNaN(acc.total) ? 0 : acc.total);
   return acc;
}, {});
  • Related