如何在javascript中将数组映射到对象中

时间:2017-09-21 12:07:13

标签: javascript arrays ecmascript-6

如何在JavaScript中将数组映射到对象? 例如,如何映射

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

进入这个

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}
]
JavaScript中的

3 个答案:

答案 0 :(得分:2)

您可以使用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);




答案 1 :(得分:0)

不知怎的这样:



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)




答案 2 :(得分:0)

您可以迭代键,然后迭代属性,并在每个索引处分配所需的值。

这可以在不事先知道的情况下使用任意数量的属性。



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; }