0

sorry before if this is an duplicate or have similarity with other post, but I cannot find problem with the same context as I have.

So I have an array of object, something like this

const queryResult = [
  { token: 'c5WKMXW8QdCFUg4q8ica' },
  { token: 'Othertoken' },
  { token: 'moreothertokens'},
]

So, i want to merge those 3 tokens into an array, something like this

['c5WKMXW8QdCFUg4q8ica', 'Othertoken', 'moreothertokens']

I am using forEach for the solution at the moment. But is there any shortcut or cleaner code?

Thank you.

Evan Gunawan
  • 387
  • 4
  • 17

3 Answers3

2

Try this:

const tokens = queryResult.map(x => x.token);
Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
2

If you have only one property in the objects, you could take a flat map approach with Object.values as callback.

const
    queryResult = [{ token: 'c5WKMXW8QdCFUg4q8ica' }, { token: 'Othertoken' }, { token: 'moreothertokens'}],
    tokens = queryResult.flatMap(Object.values);

console.log(tokens);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks for the answer. I Personally interested in the solution. Unfortunately, I think my project didn't support that yet, seeing that `flatMap` is supported in the latest ECMA Script, which my project is older and not using babel. – Evan Gunawan Jul 13 '20 at 10:32
  • thanks for letting me know `flatMap`...it seems that ES functions are popping out quicker than mushrooms. – Mario Vernari Jul 13 '20 at 12:23
1

You could use map with object destructing

const queryResult = [
  { token: "c5WKMXW8QdCFUg4q8ica" },
  { token: "Othertoken" },
  { token: "moreothertokens" },
]

const tokens = queryResult.map(({ token }) => token)

console.log(tokens)
hgb123
  • 13,869
  • 3
  • 20
  • 38