I have some data from a collection named \"service\" which has data like this:
let service_data = [
{
\"name\":\"Service 1\",
\"price\":60,
\"resou
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)
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]), []);
};
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))
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);