Home > Mobile >  Unable to manipulate the object to a specific format in Javascript
Unable to manipulate the object to a specific format in Javascript

Time:03-11

I am trying to manipulate the object into my format of object but it's not working.

I want to convert this array of objects:

let details =
[
 { tower_name: 'T1', flats: '["99", "96"]' },
 { tower_name: 'T2', flats: '["98"]' },
 { tower_name: 'T3', flats: '["505"]' }
]

And turn it into below format:

let towerFlatDetails = 
{
"T1": ["99", "96"],
"T2": ["98"],
"T3": ["505"],
}

I tried it this way, but it didn't work:

let towerFlatDetails = {}
for (let i in details)
{
    towerFlatDetails.details[i].tower_name = JSON.parse(towerFlatDetails.details[i].flats)
}

CodePudding user response:

Use Object.fromEntries:

let details =
[
 { tower_name: 'T1', flats: '["99", "96"]' },
 { tower_name: 'T2', flats: '["98"]' },
 { tower_name: 'T3', flats: '["505"]' }
];

let result = Object.fromEntries(details.map(({tower_name, flats}) =>
    [tower_name, JSON.parse(flats)]
));

console.log(result);

CodePudding user response:

towerFlatDetails.details does not exist, as towerFlatDetails is an empty object, without any properties. towerFlatDetails.details[i].tower_name would need you to have created a details array inside towerFlatDetails before it would work.

You need to write:

let details =
[
 { tower_name: 'T1', flats: '["99", "96"]' },
 { tower_name: 'T2', flats: '["98"]' },
 { tower_name: 'T3', flats: '["505"]' }
]

let towerFlatDetails = {}
for (let i of details)
{
  towerFlatDetails[i.tower_name] = JSON.parse(i.flats)
}

console.log(towerFlatDetails);

This will use the tower_name as the keys in towerFlatDetails and the flats as the values.

Also, in your loop, you need to write of instead of in. in uses the index of the entries, of uses the values of each entry.

This is the direct translation of the loop you wrote, to working code.

  • Related