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

121
Views
How to find a key with a specific value in an object in an array, and then swap that key with that value?

My goal is to write a script that goes though an array of objects. It needs to find the keys with the value "age," so that "age" become the key, and the numbers become the values. It then needs to be reformated. The reformating works just fine, but I can't change the tags without a for loop, which is not what the assignment asks.

My current code looks like this:

function mapCharacters(comiccharacters) {



const supers = comiccharacters.map(({ name, isHero, age}) => {

    for (let i = 0; i < comiccharacters.length; i++) 
    {

        for (var key in comiccharacters[i]) 
     {
         if (comiccharacters[i][key] === 'age') 
         {
             [key, comiccharacters[i][key]] = [comiccharacters[i][key], key]

         }

     }

     }
  


    if (isHero == true) {

        console.log(age);
        return "hero: " + name + ", age: " + age;

    }

    else {

        return "villain: " + name + ", age: " + age;

    }
});


console.log(supers);

}

mapCharacters([
    { name: 'Spider-Man', isHero: true, '28': 'age' },
    { name: 'Thor', isHero: true, '1500': 'age' },
    { name: 'Black Panther', isHero: true, '35': 'age' },
    { name: 'Loki', isHero: false, '1054': 'age' },
    { name: 'Venom', isHero: false, 'unknown': 'age' }
])

However, what I did with the for loop, I need to do with map functions. I would like advice as to how

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First you have to loop throught the array. Then for each object key, check if the value is age. When found, delete the property from the object and set a new one with the key age and the value key.

let mapCharacters = [
  { name: "Spider-Man", isHero: true, 28: "age" },
  { name: "Thor", isHero: true, 1500: "age" },
  { name: "Black Panther", isHero: true, 35: "age" },
  { name: "Loki", isHero: false, 1054: "age" },
  { name: "Venom", isHero: false, unknown: "age" }
];

let reorganized = mapCharacters.map(item => {
  Object.keys(item).forEach(key => {
    if (item[key] == "age") {
      delete item[key]
      item = { ...item, age: key }
    }
  })
  return item
})

console.log(reorganized)

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!