1

Here is my API data:

Home: {
  metrics: {
    aggregated_users_count: [
      {
        count: 1,
        joined_day: '2019-08-13'
      },
      {
        count: 2,
        joined_day: '2019-08-14'
      }    
    ]
  }
}

I want to assign 'count' values in a 'userCount' array and 'joined_day' in a 'registeredDate' array.

for eg:

const userCount = [1,2]
chumakoff
  • 6,807
  • 2
  • 23
  • 45

2 Answers2

2

This could be achieved by mapping your API data to the two arrays like this:

const Response = {
  Home: {
    metrics: {
      aggregated_users_count: [{
          count: 1,
          joined_day: '2019-08-13'
        },
        {
          count: 2,
          joined_day: '2019-08-14'
        }
      ]
    }
  }
};

const aggregatedUserData = Response.Home.metrics.aggregated_users_count;

/* Perform mapping to extract fields of each item to respective arrays */
const registeredDate = aggregatedUserData.map(({ joined_day }) => joined_day);
const userCount = aggregatedUserData.map(({ count }) => count);

console.log("registeredDate:", registeredDate);
console.log("userCount:", userCount);
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • 1
    You can use this condition to validate response before the use of map `Response && Response.Home && Response.Home.metrics && Response.Home.metrics.aggregated_users_count && Array.isArray(Response.Home.metrics.aggregated_users_count)`. –  Aug 29 '19 at 09:54
  • You're right - in a real world application, the response should be validated. This code snippet was just intended to convey the mapping concept with known data. I could have added validation, however that might become a distraction from the intent of the answer. – Dacre Denny Aug 29 '19 at 09:57
0

const userCount = Home.metrics.aggregated_users_count.map((data) => data.count)
Daniel Tok
  • 207
  • 1
  • 9