我有
var obj = {'b': 2, 'c': 3};
我想在该对象的开头(而不是结尾)添加一个属性:
var obj = {'a': 1, 'b': 2, 'c': 3};
有没有一种干净的方式来实现这个?我有
var obj = {'b': 2, 'c': 3};
我想在该对象的开头(而不是结尾)添加一个属性:
var obj = {'a': 1, 'b': 2, 'c': 3};
有没有一种干净的方式来实现这个?你也可以在ES6(ES2015+)中使用Object.assign()。
let obj = {'b': 2, 'c': 3};
const returnedTarget = Object.assign({a: 1}, obj);
// Object {a: 1, b: 2, c: 3}
现在你可以在ES6(ES2015+)中使用方便的扩展运算符(...),试试以下代码:
const obj = {'b': 2, 'c': 3};
const startAdded = {'a':1 , ...obj};
console.log(startAdded);
const endAdded = {...obj, 'd':4};
console.log(endAdded);
也许能帮助那些在IT领域摸索的人 :)
let obj = {'b': 2, 'c': 3};
let newObj = {'a': 1, ...obj};
JavaScript对象是无序的。没有开始或结束。如果您想要排序,请使用数组。
var arr = [
{ key: 'b', value: 2 },
{ key: 'c', value: 3 }
];
您可以使用 unshift
在其前面添加:
arr.unshift({ key: 'a', value: 1 });
var myObj = _.merge({ col1: 'col 1', col2: 'col 2'}, { col3: 'col 3', col4: 'col 4' });
{ col1: 'col 1', col2: 'col 2', col3: 'col 3', col4: 'col 4' }
如其他人所述,无法保证对象中键的顺序是否会保持不变,这取决于您对其进行的操作。但是,如果您将合并作为最后一步执行,则应该没有问题。请注意,“合并”函数将生成一个全新的对象,它不会更改您传递给它的任何对象。
var obj = {'b': 2, 'c': 3};
obj = Object.assign({a: 1}, obj);
console.log(obj); // {a: 1, b: 2, c: 3}
希望这能有所帮助。
for...in
顺序不是最初添加属性的顺序。因此,在我的项目和也许你的项目中,就所有方面而言,这是非常可预测的。// Insert Property
Object.defineProperty(
Object.prototype,
'insertProperty',
{
value: function(name, value, index){
// backup my properties
var backup = {};
// delete all properties after index
var propertyIndex = 0;
for(var propertyName in this) {
if(this.hasOwnProperty(propertyName) && propertyIndex++ >= index) {
backup[propertyName] = this[propertyName];
delete this[propertyName];
}
}
this[name] = value;
// restore all properties after index
for(var propertyName in backup) {
if(backup.hasOwnProperty(propertyName))
this[propertyName] = backup[propertyName];
}
return this; // same object; not a new object
},
enumerable: false,
});
使用方法
var obj = {'b': 2, 'c': 3};
obj.insertProperty('a',1,0); // {a:1, b:2, c:3}
笔记
在某些情况下,您可能只需按照要查看其出现的顺序创建具有所有已知属性的对象,并稍后在设置属性时而不是插入属性。
// creation
var a = {Id: null, foo: 'bar'};
// update later
if(!a.Id)
a.Id = '123';
var new_object = {};
new_object[name] = value; // The property we need at the start
for (var key in old_object) { // Looping through all values of the old object
new_object[key] = old_object[key];
delete old_object[key];
}
old_object = new_object; // Replacing the old object with the desired one
for in
枚举它们是任意的。 - Bergi