JavaScript:如何从对象数组中获取新的值数组?

时间:2019-08-29 09:41:39

标签: javascript

这是我的API数据:

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

我想在'userCount'数组中分配'count'值,在'registeredDate'数组中分配'joined_day'。

例如:

const userCount = [1,2]

2 个答案:

答案 0 :(得分:3)

可以by mapping your API data实现两个数组,如下所示:

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);

答案 1 :(得分:0)


const userCount = Home.metrics.aggregated_users_count.map((data) => data.count)