Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
Unable to manipulate the object to a specific format in Javascript

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)
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!