所以我有这样的东西:
var myArray = ["cherry", "Michigan", "potato", "Idaho", "apple", "NewYork", "Burrito", "California"]
我需要转换为:
[
{id: 1, foods: "cherry", location: "Michigan"},
{id: 2, foods: "potato", location: "Idaho"},
{id: 3, foods: "apple", location: "NewYork"},
{id: 4, foods: "burrito", location: "California"}
]
如果您的数组数据结构总是这样,则可以执行此操作:
var myArray = ["cherry", "Michigan", "potato", "Idaho", "apple", "NewYork", "Burrito", "California"]
let outputArr = []
let id = 1;
for(let i = 0; i < myArray.length -1; i +=2) {
outputArr.push({
id: id,
foods: myArray[i],
location: myArray[i+1]
})
id++;
}
console.log(outputArr)
您可以通过以下方式循环数组:
const myArray = ["cherry", "Michigan", "potato", "Idaho", "apple", "NewYork", "Burrito", "California"]
let result = []
for(let i=0; i< myArray.length -1; i+=2) {
let id = Object.keys(result).length + 1
let foods = myArray[i]
let location = myArray[i+1]
result = [...result, {id, foods, location} ]
}
console.log(result)