0

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"]
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100

2 Answers2

3

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • wow you just read my mind. I have never seen `flatMap` before (super cool), the browser recognizes it but VS code doesn't. Is it a new method? – Patricio Vargas Mar 09 '19 at 22:33
  • Indeed. You should look at the support in the supplied link. If it's not supported by your target browsers, I've added another option. You can also use a [shim](https://github.com/es-shims/Array.prototype.flatMap). – Ori Drori Mar 09 '19 at 22:35
  • Yes I saw the alternative, Google Chrome run it perfectly , but VS Code didn't recognize it. – Patricio Vargas Mar 09 '19 at 22:36
  • 1
    See this answer about flatMap and flat with typescript - https://stackoverflow.com/questions/53556409/typescript-flatmap-flat-flatten-doesnt-exist-on-type-any – Ori Drori Mar 09 '19 at 22:37
1

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; }
Ele
  • 33,468
  • 7
  • 37
  • 75