javascript 如何在javascript中的对象开头添加属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19457337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:38:59  来源:igfitidea点击:

How to add a property at the beginning of an object in javascript

javascriptobject

提问by cedivad

I have

我有

var obj = {'b': 2, 'c': 3};

And i would like to add a property at the beginning (not at the end) of that object:

我想在该对象的开头(而不是结尾)添加一个属性:

var obj = {'a': 1, 'b': 2, 'c': 3};

Is there a clean way to do that?

有没有干净的方法来做到这一点?

采纳答案by Quentin

JavaScript objects are unordered. There is no beginning or end. If you want order, use an array.

JavaScript 对象是无序的。没有开始也没有结束。如果您想要订单,请使用数组。

var arr = [
    { key: 'b', value: 2 },
    { key: 'c', value: 3 }
];

You can then add to the front of it with unshift:

然后你可以添加到它的前面unshift

arr.unshift({ key: 'a', value: 1 });

回答by Justin

You can also use Object.assign()in ES6 (ES2015+).

您还可以在 ES6 (ES2015+) 中使用Object.assign()。

let obj = {'b': 2, 'c': 3};
Object.assign({a: 1}, obj);

// Object {a: 1, b: 2, c: 3}

回答by darmis

These days you could use the cool spread operator (...) in ES6 (ES2015+), try out the following:

这些天你可以在 ES6 (ES2015+) 中使用很酷的扩展运算符 (...),尝试以下操作:

const obj = {'b': 2, 'c': 3};
   
const startAdded = {'a':1 , ...obj};
console.log(startAdded);

const endAdded = {...obj, 'd':4};
console.log(endAdded);

Might help someone out there in the wild :)

可能会帮助野外的人:)

回答by Rohit Kawade

The simplest way is to use the spread operator.

最简单的方法是使用扩展运算符。

let obj = {'b': 2, 'c': 3};
let newObj = {'a': 1, ...obj};

回答by bbeny

This Can be done using the lodashmerge function like so:

这可以使用lodash合并函数来完成,如下所示:

var myObj = _.merge({ col1: 'col 1', col2: 'col 2'}, { col3: 'col 3', col4: 'col 4' });

Your final object will look like this:

您的最终对象将如下所示:

{ col1: 'col 1', col2: 'col 2', col3: 'col 3', col4: 'col 4' }

As others mentioned, there is no guarantee that the order of the keys in the object will remain the same, depending on what you do with it. But, if you perform the merge as your final step, you should be ok. Note, the 'merge' function will produce a completely new object, it will not alter either of the objects you pass into it.

正如其他人所提到的,不能保证对象中键的顺序将保持不变,这取决于您对其进行的操作。但是,如果您将合并作为最后一步执行,则应该没问题。请注意,'merge' 函数将生成一个全新的对象,它不会改变您传递给它的任何一个对象。

回答by VangelisB

What worked for me is to use a temporary object for storing items in the desired order. For example:

对我有用的是使用临时对象按所需顺序存储项目。例如:

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

回答by Rami Ibrahim

var obj = {'b': 2, 'c': 3};
obj = Object.assign({a: 1}, obj);
console.log(obj); // {a: 1, b: 2, c: 3}

Hope this helps

希望这可以帮助

回答by toddmo

Javascript may not specify an order for properties in the language itself, but at least in my project (and perhaps yours), it certainly acts as if it does (JSON.stringify, debug watch windows, etc). I've never seen the for...inorder be anything other than the order in which the properties were originally added. So for all intents and purposes in my project, and perhaps yours, this is very predictable.

Javascript 可能不会在语言本身中指定属性的顺序,但至少在我的项目(也许是您的)中,它确实表现得好像它一样(JSON.stringify,调试监视窗口等)。for...in除了最初添加属性的顺序之外,我从未见过其他任何顺序。因此,对于我的项目中的所有意图和目的,也许是您的,这是非常可预测的。

And although this doesn't affect execution, this is a pain if you want to see a uniform list when properties of different items may be added in different order depending on how the object was created. Execution might not be the only thing that matters in project development. The ability to quickly visually inspect your objects also might matter.

虽然这不会影响执行,但如果您想看到一个统一的列表,当不同项目的属性可能会根据对象的创建方式以不同的顺序添加时,这会很痛苦。执行可能不是项目开发中唯一重要的事情。快速目视检查对象的能力也可能很重要。

Method 1 (high tech)

方法一(高科技)

If you have spread, I would use that if you don't mind another object. But if you don't have spread(like in the older google apps script), or you need to keep the original object, you can do this:

如果你有spread,如果你不介意另一个对象,我会使用它。但是如果你没有spread(就像在旧的谷歌应用程序脚本中一样),或者你需要保留原始对象,你可以这样做:

objects.js

对象.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,
});

usage

用法

  var obj = {'b': 2, 'c': 3};
  obj.insertProperty('a',1,0); // {a:1, b:2, c:3}

notes

笔记

  • You can use any indexto put the property wherever you want it. 0 puts it at the front.
  • You can certainly pull the function out and add an obj parameter if you don't like adding methods to the object prototype. In my project, adding methods to the prototype helps me; it doesn't hurt me.
  • 您可以使用 anyindex将该属性放置在您想要的任何位置。0 把它放在前面。
  • 如果您不喜欢将方法添加到object prototype. 在我的项目中,向原型添加方法对我有帮助;它不会伤害我。

Method 2 (low tech)

方法 2(低技术)

In some cases, you might be able to just create your object with all the properties you know it may eventually have in the order you want to see them appear, and later, instead of inserting the property, just set the property.

在某些情况下,您可能能够仅使用您知道它最终可能具有的所有属性按照您希望看到它们出现的顺序创建您的对象,然后,无需插入属性,只需设置该属性。

// creation
var a = {Id: null, foo: 'bar'}; 

// update later
if(!a.Id)
  a.Id = '123';