Push element value from array of objects to a variable

前端 未结 4 1674
夕颜
夕颜 2021-01-25 10:33

I have some data from a collection named \"service\" which has data like this:

let service_data = [
  {
    \"name\":\"Service 1\",
    \"price\":60,
    \"resou         


        
4条回答
  •  情歌与酒
    2021-01-25 11:16

    You can use flatMap

    const extractFlat = (arr, key) => {
        return arr.flatMap(e => e[key]);
    };
    
    let service_data = [
      {
        "name":"Service 1",
        "price":60,
        "resource_group_ids" : 
             ["5d5e5dea99d9b75ff2f78dcd","5d5e85d329782914332368c8"]
      },
      {
        "name":"Service 2",
        "price":60,
        "resource_group_ids" : ["5d5e5dea99d9b75ff2f7cfe"]
      }
    ]
    
    const resource_group_ids = extractFlat(service_data, 'resource_group_ids');
    console.log(resource_group_ids);

    or reduce on older environments

    const extractFlat = (arr, key) => {
        return arr.reduce((acc, x) => acc.concat(x[key]), []);
    };
    

提交回复
热议问题