我有
var obj = {'b': 2, 'c': 3};
我想在该对象的开头(不是最后)添加一个属性:
var obj = {'a': 1, 'b': 2, 'c': 3};
有干净的方法吗?
答案 0 :(得分:32)
您也可以在ES6(ES2015 +)中使用Object.assign()。
let obj = {'b': 2, 'c': 3};
Object.assign({a: 1}, obj);
// Object {a: 1, b: 2, c: 3}
答案 1 :(得分:10)
JavaScript对象是无序的。没有开始或结束。如果您想订购,请使用数组。
var arr = [
{ key: 'b', value: 2 },
{ key: 'c', value: 3 }
];
然后,您可以使用unshift
:
arr.unshift({ key: 'a', value: 1 });
答案 2 :(得分:7)
这几天,您可以在ES6(ES2015 +)中使用酷传播算子(...),请尝试以下方法:
const obj = {'b': 2, 'c': 3};
const startAdded = {'a':1 , ...obj};
console.log(startAdded);
const endAdded = {...obj, 'd':4};
console.log(endAdded);
可能会在野外帮助某人:)
答案 3 :(得分:4)
这可以使用lodash合并功能完成,如下所示:
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' }
正如其他人所提到的,无法保证对象中键的顺序将保持不变,具体取决于您使用它的方式。但是,如果您执行合并作为最后一步,那么您应该没问题。注意,'merge'函数将生成一个全新的对象,它不会改变你传递给它的任何对象。
答案 4 :(得分:3)
最简单的方法是使用扩展运算符。
let obj = {'b': 2, 'c': 3};
let newObj = {'a': 1, ...obj};
答案 5 :(得分:2)
var obj = {'b': 2, 'c': 3};
obj = Object.assign({a: 1}, obj);
console.log(obj); // {a: 1, b: 2, c: 3}
希望这会有所帮助
答案 6 :(得分:0)
对我有用的是使用临时对象以所需顺序存储项目。 例如:
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
答案 7 :(得分:0)
JavaScript可能未在语言本身中指定属性的顺序,但至少在我的项目(可能还有您的项目)中,JavaScript的确表现得确实如此(JSON.stringify
,调试监视窗口等)。我从未见过for...in
顺序与最初添加属性的顺序不同。因此,对于我项目(甚至您的项目)中的所有意图和目的,这都是可以预见的。
尽管这不影响执行,但是如果您希望看到一个统一的列表,而不同的项的属性可能根据对象的创建方式以不同的顺序添加时,这会很麻烦。在项目开发中,执行并不是唯一重要的事情。快速视觉检查对象的能力也可能很重要。
如果您有spread
,如果您不介意其他对象,我会使用它。但是,如果您没有spread
(例如在旧版Google Apps脚本中),或者您需要保留原始对象,则可以执行以下操作:
objects.js
// 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}
注释
index
将属性放置在所需的位置。 0放在最前面。object prototype
添加方法,则可以肯定地拉出函数并添加obj参数。在我的项目中,向原型添加方法对我有帮助。不会伤害我的。在某些情况下,您可以按照自己希望最终看到的所有属性来创建对象,并按其希望的顺序显示它们,然后,无需插入该属性,只需设置该属性即可。
// creation
var a = {Id: null, foo: 'bar'};
// update later
if(!a.Id)
a.Id = '123';