如何从数组创建JS对象

时间:2020-10-04 10:49:15

标签: javascript

我有两个数组

const time = ['00:00', '00:30', '01:00', '01:30']

const cost = [1.40, 5.00, 2.00, 3.00]

我想将它们合并成具有如下键的对象数组:

result = [
    {
        time: '00:00',
        cost: 1.40
    },
    {
        time: '00:30',
        cost: 5.00
    },
    {
        time: '01:00',
        cost: 2.00
    },
    {
        time: '01:30',
        cost: 3.00
    }
]

4 个答案:

答案 0 :(得分:4)

您可以尝试使用Array.prototype.map()

map()方法创建一个新数组,其中填充了在调用数组中每个元素上调用提供的函数的结果。

const time = ['00:00', '00:30', '01:00', '01:30'];
const cost = [1.40, 5.00, 2.00, 3.00];
var result = time.map((t, i)=>({time: t, cost: cost[i]}));
console.log(result);

答案 1 :(得分:0)

可以通过以下方式完成:-

const time = ['00:00', '00:30', '01:00', '01:30']
const cost = [1.40, 5.00, 2.00, 3.00]


let array = []
for(let i=0; i<4; i++){
  let obj = {}
  obj.time = time[i]
  obj.cost = cost[i]
  array.push(obj)
}
console.log(array)

输出-

[
  { time: '00:00', cost: 1.4 },
  { time: '00:30', cost: 5 },
  { time: '01:00', cost: 2 },
  { time: '01:30', cost: 3 }
]

答案 2 :(得分:0)

您可以循环浏览两个数组之一,然后将对象填充到声明的数组中,如下所示。

const time = ['00:00', '00:30', '01:00', '01:30'];
const cost = [1.4, 5.0, 2.0, 3.0];

let objArr = [];

time.forEach((t, i) => {
  objArr[i] = {
    time: t,
    cost: cost[i],
  };
});

console.log(objArr);

答案 3 :(得分:0)

Current Working Directory