Push element value from array of objects to a variable

前端 未结 4 1673
夕颜
夕颜 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:13

    Using .reduce:

    let service_data = [{
        "name": "Service 1",
        "price": 60,
        "resource_group_ids": ["5d5e5dea99d9b75ff2f78dcd", "5d5e85d329782914332368c8"]
      },
      {
        "name": "Service 2",
        "price": 60,
        "resource_group_ids": ["5d5e5dea99d9b75ff2f7cfe"]
      }
    ]
    
    const resource_groups = service_data.reduce(function(result, item) {
      result.concat(item.resource_group_ids)
    }, [])
    
    console.log(resource_groups)

    0 讨论(0)
  • 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]), []);
    };
    
    0 讨论(0)
  • 2021-01-25 11:17

    You could use flatMap

    const resource_groups = service_data.flatMap(o => o.resource_group_ids)
    

    const service_data = [{"name":"Service 1","price":60,"resource_group_ids":["5d5e5dea99d9b75ff2f78dcd","5d5e85d329782914332368c8"]},{"name":"Service 2","price":60,"resource_group_ids":["5d5e5dea99d9b75ff2f7cfe"]}]
    
    const resource_groups = service_data.flatMap(o => o.resource_group_ids)
    
    console.log(resource_groups)

    If flatMap is not supported, use concat and spread syntax to merge the 2D array returned by map

    const resource_groups = [].concat(...service_data.map(o=> o.resource_group_ids))
    
    0 讨论(0)
  • 2021-01-25 11:20

    You can achieve this with .map(), .join() and .split()

        const service_data = [
          {
            name: 'Service 1',
            price: 60,
            resource_group_ids:
              ['5d5e5dea99d9b75ff2f78dcd', '5d5e85d329782914332368c8']
          },
          {
            name: 'Service 2',
            price: 60,
            resource_group_ids: ['5d5e5dea99d9b75ff2f7cfe']
          },
        ];
        
        const result = service_data.map((r) => { return r.resource_group_ids; 
                   }).join(',').split(',');
        console.log(result);

    0 讨论(0)
提交回复
热议问题