如何动态地向对象添加数组?

时间:2020-01-11 11:05:05

标签: javascript arrays javascript-objects

我要实现的目标

我试图将数组动态添加到对象。也就是说,从

开始
 {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");

但这不起作用。

问题

如何向对象添加数组?

2 个答案:

答案 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)

  1. 如果状态属性存在于对象中,则它遵循以下代码
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' }
  1. 如果状态属性不存在于对象中,则遵循以下代码
let car = {colour: "white", type: "electric"};
if(car.status){
  car.status = "sold";
}
console.log(car)
// o/p { colour: 'white', type: 'electric' }
  1. 如果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' ] }