我有一个这样的对象。
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"
}
}
答案 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)
您可以通过多种方式向属性添加新属性
myObj['cars']['car4'] = 'Audi';
myObj['cars'].car4 = 'Audi';
myObj.cars['car4'] = 'Audi';
myObj.cars.car4 = 'Audi';
Object.assign():
Object.assign(myObj.cars, {car4: 'Audi'});
新的ECMA 7扩展运算符(...
):
myObj.cars = { ...myObj.cars, car4: 'Audi' }
使用Lodash _ = require('lodash')
:
_.set(myObj, ['cars', 'car4'], 'Audi');
lodash.js
也可以创建新属性的属性:
_.set(myObj, ['newProp', 'newCar', 'newBrand'], 'Think');