这是我的对象文字:
var obj = {key1: value1, key2: value2};
如何将值为3的字段key3添加到对象中?
这是我的对象文字:
var obj = {key1: value1, key2: value2};
如何将值为3的字段key3添加到对象中?
当前回答
大多数答案中已经提到了两种最常用的方法
obj.key3 = "value3";
obj["key3"] = "value3";
定义属性的另一种方法是使用Object.defineProperty()
Object.defineProperty(obj, 'key3', {
value: "value3", // undefined by default
enumerable: true, // false by default
configurable: true, // false by default
writable: true // false by default
});
当您希望在定义属性时拥有更多控制权时,此方法非常有用。用户可以将定义的属性设置为可枚举、可配置和可写。
其他回答
arr.key3 = value3;
因为你的arr不是一个数组。。。这是一个原型对象。真正的数组应该是:
var arr = [{key1: value1}, {key2: value2}];
但这仍然不正确。实际上应该是:
var arr = [{key: key1, value: value1}, {key: key2, value: value2}];
示例显示的是对象,而不是数组。在这种情况下,将字段添加到Object的首选方法是只分配给它,如下所示:
arr.key3 = value3;
var employees = [];
employees.push({id:100,name:'Yashwant',age:30});
employees.push({id:200,name:'Mahesh',age:35});
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
var injectObj = {isActive:true, timestamp:new Date()};
// function to inject key values in all object of json array
function injectKeyValueInArray (array, keyValues){
return new Promise((resolve, reject) => {
if (!array.length)
return resolve(array);
array.forEach((object) => {
for (let key in keyValues) {
object[key] = keyValues[key]
}
});
resolve(array);
})
};
//call function to inject json key value in all array object
injectKeyValueInArray(arrOfObj,injectObj).then((newArrOfObj)=>{
console.log(newArrOfObj);
});
输出如下:-
[ { name: 'eve',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'john',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'jane',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z } ]
我们可以通过多种方式向JavaScript对象添加键/值对。。。
案例1:展开对象使用此选项,我们可以同时向对象添加多个key:value。
常量矩形={width:4,height:6};常量立方体={…矩形,长度:7};const cube2={…矩形,长度:7,笔划:2};console.log(“立方体2:”,立方体2);console.log(“Cube:”,立方体);console.log(“矩形:”,矩形);
案例2:使用点符号
var矩形={width:4,height:6};直角长度=7;console.log(矩形);
案例3:使用[平方]符号
var矩形={width:4,height:6};矩形[“长度”]=7;console.log(矩形);