如何将值推入对象

时间:2018-09-07 07:40:52

标签: javascript object

我有一个这样的对象。

var myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}

我知道要添加这样的条目。

myObj['model']='XUV';

但是我想在cars对象中添加一个条目(将新的“ Audi”汽车添加为car4) 你能告诉我如何添加吗?

最终输出应该像。

 var myObj = {
      "name":"John",
      "age":30,
      "cars": {
        "car1":"Ford",
        "car2":"BMW",
        "car3":"Fiat",
        "car4":"Audi"
      }

}

5 个答案:

答案 0 :(得分:1)

只是

myObj.cars["car4"] = "Audi";

答案 1 :(得分:1)

您需要先访问cars对象,然后在其中分配一个新的key-value,因此请使用myObj.cars.car4 = 'Audi'或与[]myObj.cars['car4'] = 'Audi'一起使用。

var myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
myObj.cars.car4 = 'Audi';
console.log(myObj);

答案 2 :(得分:1)

2017年答案:Object.assign()

var obj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
};

Object.assign(obj.cars, {car4: "Audi"});

2018对象传播算子{...}

var obj = {
      "name":"John",
      "age":30,
      "cars": {
        "car1":"Ford",
        "car2":"BMW",
        "car3":"Fiat"
      }
    };

obj.cars = { ...obj.cars, car4: "Audi" }

答案 3 :(得分:1)

在我看来,这是一个错误构建的JSON。我将使用数组而不是命名属性"car" + someIndex

var myObj =
{
    "name":"John",
    "age":30,
    "cars": [
        { "brand":"Ford" },
        { "brand":"BMW" },
        { "brand":"Fiat" }
    ]
}
myObj.cars.push({ "brand":"Renault" });
console.log(myObj);

答案 4 :(得分:1)

您可以通过多种方式向属性添加新属性

  1. myObj['cars']['car4'] = 'Audi';

  2. myObj['cars'].car4 = 'Audi';

  3. myObj.cars['car4'] = 'Audi';

  4. myObj.cars.car4 = 'Audi';

  5. Object.assign():

    Object.assign(myObj.cars, {car4: 'Audi'});

  6. 新的ECMA 7扩展运算符(...):

    myObj.cars = { ...myObj.cars, car4: 'Audi' }

  7. 使用Lodash _ = require('lodash')

    _.set(myObj, ['cars', 'car4'], 'Audi');

lodash.js也可以创建新属性的属性:

_.set(myObj, ['newProp', 'newCar', 'newBrand'], 'Think');