简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM