4 回答

TA貢獻1911條經驗 獲得超7個贊
您可以嘗試使用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);

TA貢獻1890條經驗 獲得超9個贊
const time = ['00:00', '00:30', '01:00', '01:30'];
const nums = [1.99, 5.11, 2.99, 3.45 ];
const newArray = [];
time.forEach((element, index) => {
newArray.push({
time: element,
cost: nums[index]
})
})
console.log(newArray)

TA貢獻1858條經驗 獲得超8個贊
可以通過以下方式完成:-
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 }
]

TA貢獻1797條經驗 獲得超6個贊
您可以遍歷兩個數組之一,然后將對象填充到聲明的數組中,如下所示。
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);
添加回答
舉報