1

How to map array into object in JavaScript? For example how to map this

{
  name: [1,2,3,4,5,6],
  uv: [300,-145,-100,-8,100,9],
  pv: [456,230,345,450,312,235]
}

into this

data = [
  {name: '1', uv: 300, pv: 456},
  {name: '2', uv: -145, pv: 230},
  {name: '3', uv: -100, pv: 345},
  {name: '4', uv: -8, pv: 450},
  {name: '5', uv: 100, pv: 321},
  {name: '6', uv: 9, pv: 235}
]

in JavaScript

Barny
  • 383
  • 1
  • 3
  • 13

3 Answers3

2

You can use array#map

var obj = {
 name:[1,2,3,4,5,6],
 uv:[300,-145,-100,-8,100,9],
 pv:[456,230,345,450,312,235]
};

var result = obj.name.map(function(v,i){
  return {name: v, uv: obj.uv[i], pv: obj.pv[i]};
});

console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Somehow like this:

var first = {
 name:[1,2,3,4,5,6],
 uv:[300,-145,-100,-8,100,9],
 pv:[456,230,345,450,312,235]
}

var data = [];

first.name.forEach((item, i) => {
  data.push({
    name: first.name[i],
    uv: first.uv[i],
    pv: first.pv[i]
  })
})

console.log(data)
P.S.
  • 15,970
  • 14
  • 62
  • 86
0

You could iterate the keys and then the properties and assign at each index the wanted values.

This works with an arbitrary count of properties without knowing in advance.

var data = { name: [1, 2, 3, 4, 5, 6], uv: [300, -145, -100, -8, 100, 9], pv: [456, 230, 345, 450, 312, 235] },
    result = Object
        .keys(data)
        .reduce((r, k) => (data[k].forEach((v, i) => (r[i] = r[i] || {})[k] = v), r), []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392