Javascript-将字符串数组映射到具有多个对象属性的对象数组

问题描述 投票:0回答:2

所以我有这样的东西:

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"}
]
javascript
2个回答
0
投票

如果您的数组数据结构总是这样,则可以执行此操作:

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)

0
投票

您可以通过以下方式循环数组:

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)
© www.soinside.com 2019 - 2024. All rights reserved.