Ian
Ian

Reputation: 354

How to turn json to array without using key

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?

Upvotes: 1

Views: 90

Answers (2)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21891

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)

Upvotes: 0

punksta
punksta

Reputation: 2808

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

const result = arr.map(Object.values)

console.log(result);

Upvotes: 6

Related Questions