Reputation: 5522
I need to know if there's a fancy way to return an array of strings created by the properties of an array of objects. The property of those objects it's also an array.
E.g Data:
[
{
servicesOffered: ["x","Y"]
},
{
servicesOffered: ["z","w"]
}
]
I tried to be fancy using the spread operator but doesn't work. I know I can iterate again the array of servicesOffered, but I don't know if there's a fancier or better way to do this.
Code:
getServices(results: Business[]): string[] {
return results.map(({ servicesOffered }) => {
const t = servicesOffered;
return ...t;
});
}
Expected Output
["x","Y","z","w"]
Upvotes: 0
Views: 47
Reputation: 33726
Using the function reduce
.
let arr = [ { servicesOffered: ["x","Y"] }, { servicesOffered:["z","w"] }],
result = arr.reduce((a, {servicesOffered}) => a.concat(servicesOffered), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 191976
Use Array.flatMap()
instead of map:
function getServices(results) {
return results.flatMap(({ servicesOffered }) => servicesOffered);
}
const data = [{"servicesOffered":["x","Y"]},{"servicesOffered":["z","w"]}];
const result = getServices(data);
console.log(result);
If flatMap is not supported, you can use Array.map()
with spread and Array.concat()
to flatten the array:
function getServices(results) {
return [].concat(...results.map(({ servicesOffered }) => servicesOffered));
}
const data = [{"servicesOffered":["x","Y"]},{"servicesOffered":["z","w"]}];
const result = getServices(data);
console.log(result);
Upvotes: 3