Push element value from array of objects to a vari

2020-04-19 06:56发布

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

let service_data = [
  {
    "name":"Service 1",
    "price":60,
    "resource_group_ids" : 
         ["5d5e5dea99d9b75ff2f78dcd","5d5e85d329782914332368c8"]
  },
  {
    "name":"Service 2",
    "price":60,
    "resource_group_ids" : ["5d5e5dea99d9b75ff2f7cfe"]
  }
]

I want to push the resource_group_ids in a variable let say resource_groups. I don't want to loop resource_group_ids inside service_data.

标签: javascript
4条回答
▲ chillily
2楼-- · 2020-04-19 07:24

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]), []);
};
查看更多
在下西门庆
3楼-- · 2020-04-19 07:29

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))
查看更多
smile是对你的礼貌
4楼-- · 2020-04-19 07:36

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)

查看更多
一夜七次
5楼-- · 2020-04-19 07:39

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

查看更多
登录 后发表回答