Search code examples
arraysobjectkey-value

Separate an object in a array of objects


Im consuming data from an API

"stats": [
{
  "base_stat": 48,
  "effort": 1,
  "stat": {
    "name": "hp",
    "url": "https://pokeapi.co/api/v2/stat/1/"
  }
},
{
  "base_stat": 48,
  "effort": 0,
  "stat": {
    "name": "attack",
    "url": "https://pokeapi.co/api/v2/stat/2/"
  }
}]

So when i recieve this, im doing =>

const selectedStats = stats.reduce(
(acc, stat) => ({ ...acc, [stat.stat.name]: stat.base_stat }),
{} ); 
    // OUTPUT => stats: {
attack: 48
hp: 48 }

But now im trying to separate an object in a array of objects, like

[{attack: 81}, {hp: 48}, etc]

but i don't know how to do it

Sorry if this is a large question but i don't get the solve. Thanks!


Solution

  • Just mapping the result of Object.entries() would do it:

    const stats = {
      attack: 48,
      hp: 48
    };
    
    const data = Object.entries(stats).map(([k, v]) => ({[k]: v}));
    
    console.log(data);

    You don't need the intermediate reduce() though. Since you're starting off with an array, you can do everything in a single map() operation:

    const stats = [{
      "base_stat": 48,
      "effort": 1,
      "stat": {
        "name": "hp",
        "url": "https://pokeapi.co/api/v2/stat/1/"
      }
    }, {
      "base_stat": 48,
      "effort": 0,
      "stat": {
        "name": "attack",
        "url": "https://pokeapi.co/api/v2/stat/2/"
      }
    }];
    
    const data = stats.map(({base_stat, stat: {name}}) => ({[name]: base_stat}));
    
    console.log(data);