Skip to content
Advertisement

Manipulating an API response to have part of the Object as a Key?

I have data that comes back from an API as an array of Objects.

const data = 
  [

      { 
        name: "Charles",
        age: 42, 
        height: 76
      },
      { 
        name: "Jim",
        age: 32, 
        height: 56
      },
      { 
        name: "Ed",
        age: 22, 
        height: 76
      }
  ]

rather than just returning that, return data, I’d like to have it where the name is the key so that I can do a lookup on data, like data["Jim"] and get the object back.

const data = 
      [
         {
          "Charles": 
             { 
               age: 42, 
               height: 76
            },
         },
         {
          "Jim": 
             { 
               age: 32, 
               height: 56
            },
         }
     ]

how can I manipulate the data to come back that way after getting it back from the API in the original format listed first?

Advertisement

Answer

What you’re looking for is this

const result = data.reduce((acc, curr) => ({...acc, [curr.name]: {age: curr.age, height: curr.height}}), {});

now you can access like result['Jim']. You needed an object, not an array.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement