我要实现的目标
我试图将数组动态添加到对象。也就是说,从
开始 {colour: "white", type: "electric"};
以
结尾{colour: "white", type: "electric", owners: ["person1", "person2", "person3"] };
请在下面考虑以下对象
let car = {colour: "white", type: "electric"};
如果要向此对象添加另一个属性,则可以检查它是否存在。然后添加到其中,如下所示。
if( typeof car.status === "undefined")
car.status = "sold";
我尝试过的事情
使用以上逻辑,我尝试了以下操作
let car = {
colour: "white",
type: "electric"
};
if (typeof car.owners === "undefined")
car.owners.push("person1");
但这不起作用。
问题
如何向对象添加数组?
答案 0 :(得分:4)
要将数组添加到对象,请创建该数组并将其分配给属性:
let car = {
colour: "white",
type: "electric"
};
if (typeof car.owners === "undefined") {
// vvvvvvvvvvv----- creates the array
car.owners = ["person1"];
// ^^^^^^^^^--- assigns it to the property
}
console.log(car);
如果以后要添加到该数组,则可以使用push
。但是数组必须首先存在。例如:
// `person` has the person to add...
if (typeof car.owners === "undefined") {
car.owners = [person];
} else {
car.owners.push(person);
}
也就是说,最好避免不必要地更改对象的形状。我只是从一个空数组开始,然后删除if
:
let car = {
colour: "white",
type: "electric",
owners: [] // <=== Empty array
};
car.owners.push("person1");
console.log(car);
答案 1 :(得分:3)
- 如果状态属性存在于对象中,则它遵循以下代码
let car = {colour: "white", type: "electric",status:"somethings!"};
if(car.status){
car.status = "sold";
}
console.log(car)
// o/p { colour: 'white', type: 'electric', status: 'sold' }
- 如果状态属性不存在于对象中,则遵循以下代码
let car = {colour: "white", type: "electric"};
if(car.status){
car.status = "sold";
}
console.log(car)
// o/p { colour: 'white', type: 'electric' }
- 如果Array属性检查对象内部,则应遵循以下示例代码
let car = {colour: "white", type: "electric"};
if(car.owners){
// when the owners property exist
car.owners.push("person1");
} else {
// when the owners property does not exist
car.owners = [];
car.owners.push("person2");
}
console.log(car)
// o/p { colour: 'white',type: 'electric',owners: [ 'person2' ] }