0

I have an array of objects called rate. Within each rate object is a tags property. I would like to combine the tags from all objects into new array such that expected output is:

["TAG_1_2_3_4", "TAG_7_8_9_0", "TAG_4_5_6"]

Is there a simpler/cleaner way than using forEach to loop through and then push to array?

Example:

[
  {
    "price": "123",
    "tags": [
      "TAG_1_2_3_4",
      "TAG_7_8_9_0"
    ]
  },
  {
    "price":"456",
    "tags":[
      "TAG_4_5_6"
    ]
  }
]
1
  • Any code to show? Commented Nov 30, 2020 at 20:06

1 Answer 1

3

Use Array.flatMap() to get the tags and flatten them to a single array:

const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]

const result = arr.flatMap(o => o.tags)

console.log(result)

If Array.flatMap() is not supported, you can use Array.reduce() with Array.concat():

const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]

const result = arr.reduce((acc, o) => acc.concat(o.tags), [])

console.log(result)

Or get all tags with Array.map(), and flatten by spreading into Array.concat():

const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]

const result = [].concat(...arr.map(o => o.tags))

console.log(result)

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

4 Comments

awesome! i see flatMap is not supported in IE. Is there another way?
Which version of IE?
according to this, flatMap is not supported in any IE developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Which version of IE do you need to support?

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.