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"]

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
Yes I saw the alternative, Google Chrome run it perfectly , but VS Code didn't recognize it.
See this answer about flatMap and flat with typescript - stackoverflow.com/questions/53556409/…
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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.