我有一个需要更改为数组的对象。最好的方法是什么?
var x = {
vehicle: {
manufacturer: "Volkswagen",
carlineName: "Golf",
}
}
我想要以下结果
var x = {
vehicle: [
{
manufacturer: "Volkswagen",
carlineName: "Golf",
}
]
}
答案 0 :(得分:1)
对于此示例,您可以编写:
var x = {
vehicle: {
manufacturer: "Volkswagen",
carlineName: "Golf",
}
}
x.vehicle = [x.vehicle]
console.log(x)
x.vehicle
得到
{
manufacturer: "Volkswagen",
carlineName: "Golf",
}
和方括号 [ x.vehicle
] 将该值放入数组:
[{
manufacturer: "Volkswagen",
carlineName: "Golf",
}]
我们想用这个新值重新分配x.vehicle,所以我们使用x.vehicle = [x.vehicle]
答案 1 :(得分:0)
您只需构建一个将对象封装在[
和]
中的新对象,即可使其成为数组。
var x = {
vehicle: {
manufacturer: "Volkswagen",
carlineName: "Golf",
}
}
var output = {
vehicle: [x.vehicle]
};
console.log(output);
这可能比变异现有对象更安全。