我有一个类似于下面的JSON对象:
vehicles:
{
trucks: [
"Ford",
"Toyota",
"Dodge",
],
suvs: [
"Honda",
"GMC",
],
cars: [
"Pontiac",
"Lotus",
"Aston-Martin",
"Porsche",
"Subaru"
]
}
我想循环使用它并创建我自己的对象,但是如果不为每种类型的车辆使用三个不同的循环,我无法找到如何做到这一点。
以下是我的尝试:
let vehicleObject = {
vehicles: []
}
// I'm getting the response back from a http request
Object.keys(body.vehicles).forEach(function (k) {
for (let i = 0; i < body.vehicles.k.length; i++) {
vehicleObject.vehicles.push({
vehicle_type: k,
manufacturer: body.vehicles.k[i]
});
}
});
但是,这只会导致我无法读取未定义的属性长度。我知道我可以通过一个或三个开关实现这个目标,但如果可能的话,我想学习一种更有效的方法。谢谢。
答案 0 :(得分:1)
循环应该是这样的:
Object.keys(body.vehicles).forEach(function (k) {
for (let i = 0; i < body.vehicles[k].length; i++) {
vehicleObject.vehicles.push({
vehicle_type: k,
manufacturer: body.vehicles[k][i]
});
console.log(vehicles[k].length)
}
});
当您遍历每个键时,您将获得k中键的名称,然后从body.vehicles对象获取数组,您需要执行类似body.vehicles [k]的操作。
答案 1 :(得分:0)
要为范围声明全局变量,您应该使用var
而不是let
var vehicleObject = {
vehicles: []
};
let
只能在{...}
块内访问,就像您在for {...}
循环中使用它一样。
答案 2 :(得分:0)
看起来你想要一个对象数组,例如:
[{ vehicle_type: 'suvs', manufacturer: 'Honda' }, ... ]
假设body
包含车辆对象:
const { vehicles } = body
const vehicleTypes = Object.keys(vehicles)
const getManufacturers = type => vehicles[type]
const createVehicle = (type, mf) => ({ vehicle_type: type, manufacturer: mf })
let flattenedVehicles = []
vehicleTypes.forEach(type => {
flattenedVehicles.push(
getManufacturers(type).map(mf => createVehicle(type, mf))
)
})
// flattenedVehicles now has desired array