1

I have this array of objects

[{
    "A": "thisA",
    "B": "thisB",
    "C": "thisC"
}, {
    "A": "thatA",
    "B": "thatB",
    "C": "thatC"
}]

I'm trying to get this format as an end result: [["thisA","thisB","thisC"], ["thatA","thisB","thatC"]]

I know we can use map() function with the specific key(A, B, C).

newarray = array.map(d => [d['A'], d['B'], d['C']])

But I need a common function to transfer it without using the key, because the content of array will be different, the key will be different. Is there any good solution?

3
  • Please post what you have tried? Commented Dec 21, 2018 at 8:23
  • 3
    arrayOfObjects.map(Object.values) Commented Dec 21, 2018 at 8:24
  • Possible duplicate of How to convert JSON to Array in Javascript Commented Dec 21, 2018 at 8:33

2 Answers 2

6

const arr = [{
  "A": "thisA",
  "B": "thisB",
  "C": "thisC"
}, {
  "A": "thatA",
  "B": "thatB",
  "C": "thatC"
}]

const result = arr.map(Object.values)

console.log(result);

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

2 Comments

amazing, I really do not know there is a such method. great thx!
you may find Object.keys and Object.entries interesting too. @lan
0

I've upvoted punksta for elegant solution, but this is how I would do that in automatic mode (without thinking how to make it elegant):

const src = [{
    "A": "thisA",
    "B": "thisB",
    "C": "thisC"
}, {
    "A": "thatA",
    "B": "thatB",
    "C": "thatC"
}]

const result = src.map(o => Object.keys(o).map(k => o[k]))

console.log(result)

2 Comments

I wouldn't say the other answer is to make it elegant, I'll say efficient, and even more readable than this.
@LGSon You are not wrong. I added my answer just because I wanted to. Because of reasons. And for comparison also, maybe.

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.