1

Im trying to get a list of individual tags from the below but i keep getting undefined. What am i doing wrong?

initialState = [{name: "John",tags: ["primary", "secondary"]}, {name: "Mark",tags: ["primary"]}];

let tags = initialState.forEach((el) => {
  if (el.tags) {
    el.tags.map((tag) => {
      return tag;
    }, []);
  }
})
console.log(tags);

Expected Result

tags = ["primary","secondary","primary"]

1
  • 1
    Array.prototype.forEach doesn't return anything. Your inner map is also an useless expression statement, because the return is immediately discarded. Commented Mar 11, 2021 at 18:02

2 Answers 2

1

.forEach doesn't return an array. To get all the tags in one list, you can use .flatMap as follows:

const initialState = [
  { name: "John", tags: ["primary", "secondary"] },
  { name: "Mark", tags:["primary"] }
];

const tags = initialState.flatMap(({ tags = [] }) => tags);   

console.log(tags);

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

Comments

0

Or, alternatively to the other answer using map() and then flat()

initialState = [{name: "John",tags: ["primary", "secondary"]}, {name: "Mark",tags: ["primary"]}];

let tags = initialState.map(el=>[...el.tags]).flat();
console.log(tags);

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.