我有
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);
可能会帮助野外的人:)
JavaScript 对象是无序的。没有开始也没有结束。如果你想要顺序,请使用数组。
var arr = [
{ key: 'b', value: 2 },
{ key: 'c', value: 3 }
];
unshift
添加到它的前面:
arr.unshift({ key: 'a', value: 1 });
这可以使用 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' }
正如其他人提到的,不能保证对象中键的顺序保持不变,具体取决于您对其执行的操作。但是,如果您将合并作为最后一步执行,那么应该没问题。请注意,“合并”函数将生成一个全新的对象,它不会更改您传递给它的任何对象。
var obj = {'b': 2, 'c': 3};
obj = Object.assign({a: 1}, obj);
console.log(obj); // {a: 1, b: 2, c: 3}
希望这有帮助
Javascript 可能不会指定语言本身的属性顺序,但至少在我的项目(也许是你的项目)中,它的行为肯定就像它指定的那样(
JSON.stringify
,调试监视窗口等)。我从未见过 for...in
顺序与最初添加属性的顺序不同。因此,对于我的项目(或许还有您的项目)的所有意图和目的而言,这是非常可预测的。
虽然这不会影响执行,但如果您想看到一个统一的列表,因为不同项目的属性可能会根据对象的创建方式以不同的顺序添加,那么这会很痛苦。执行可能不是项目开发中唯一重要的事情。快速目视检查物体的能力也可能很重要。
如果您有
spread
,如果您不介意其他物体,我会使用它。但是如果你没有spread
(就像在旧的谷歌应用程序脚本中一样),或者你需要保留原始对象,你可以这样做:
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';
对我有用的是使用临时对象以所需的顺序存储项目。 例如:
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
let list = {value: 1, rest: {value: 2, rest: {value: 3, rest: null}}};
let newElement = {names: 'arnold'};
function prepend(element, obj) {
return {...element, ...obj}
}
let newList = prepend(newElement, list);
// {names: 'arnold', value: 1,rest: { value: 2, rest: { value: 3, rest: null }}