JokerMartini
JokerMartini

Reputation: 6147

Convert a list of lists into a list of dictionaries using Javascript

Is there a built in way, using javascript, to convert a list of lists, into a list of dictionaries?

Before

[
   [
      "x", 
      "y", 
      "z",  
      "total_count", 
      "total_wins"
   ], 
   [
      25.18, 
      24.0, 
      27520.0, 
      16, 
      6, 
   ], 
   [
      25.899, 
      24.0, 
      27509.0, 
      336, 
      8
   ], 
   [
      26.353, 
      26.0, 
      27256.0, 
      240.0, 
      15 
   ], 
   [
      119.0, 
      5.0, 
      6.0, 
      72, 
      0
   ]
]

After

[
   {
      "x": 25.18, 
      "y": 24.0, 
      "z": 27520.0, 
      "total_count": 16, 
      "total_wins": 6, 
   }, 
   {
      "x": 25.899, 
      "y": 24.0, 
      "z": 27509.0, 
      "total_count": 336, 
      "total_wins": 8
   }, 
   {
      "x": 26.353, 
      "y": 26.0, 
      "z": 27256.0, 
      "total_count": 240.0, 
      "total_wins": 15 
   }, 
   {
      "x": 119.0, 
      "y": 5.0, 
      "z": 6.0, 
      "total_count": 72, 
      "total_wins": 0
   }
]

Upvotes: 0

Views: 350

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can use rest operator, map and Object.fromEntries

let data = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]];

let [keys, ...rest] = data

let final = rest.map(inp => Object.fromEntries(inp.map((value, index) => [keys[index], value])))

console.log(final)


If you're working on environment which doesn't support Object.fromEntries then you can use reduce

let data = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]];

let [keys, ...rest] = data

let buildObject = (valueArr) => {
  return valueArr.reduce((op, inp, index) => {
    op[keys[index]] = inp
    return op
  }, {})
}

let final = rest.map(inp => buildObject(inp, keys))

console.log(final)

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

Maybe not build in, but there is a way

const input = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]];

const keys = input.shift();
console.log(input.map(values => Object.fromEntries(keys.map((key, idx) => [
	key,
	values[idx]
]))));

Upvotes: 2

Related Questions