简体   繁体   English

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

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

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?有没有干净的方法来做到这一点?

You can also use Object.assign() in ES6 (ES2015+).您还可以在 ES6 (ES2015+) 中使用Object.assign( )。

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

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

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 :)可能会帮助野外的人:)

The simplest way is to use the spread operator.最简单的方法是使用扩展运算符。

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

JavaScript objects are unordered. JavaScript 对象是无序的。 There is no beginning or end.没有开始也没有结束。 If you want order, use an array.如果您想要订单,请使用数组。

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 });

This Can be done using the lodash merge 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' 函数将产生一个全新的对象,它不会改变你传递给它的任何一个对象。

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

Hope this helps希望这可以帮助

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

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). Javascript 可能不会在语言本身中指定属性的顺序,但至少在我的项目(也许是你的)中,它确实表现得好像它一样( JSON.stringify ,调试观察窗口等)。 I've never seen the for...in order be anything other than the order in which the properties were originally added.我从未见过for...in order 不是最初添加属性的顺序。 So for all intents and purposes in my project, and perhaps yours, this is very predictable.因此,对于我项目中的所有意图和目的,也许是您的项目,这是非常可预测的。

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.如果你已经spread ,如果你不介意另一个对象,我会使用它。 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 (就像在旧的谷歌应用程序脚本中一样),或者你需要保留原始对象,你可以这样做:

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 index to put the property wherever you want it.您可以使用任何index将属性放置在您想要的任何位置。 0 puts it at the front. 0 把它放在前面。
  • You can certainly pull the function out and add an obj parameter if you don't like adding methods to the object prototype .如果您不喜欢向object prototype添加方法,您当然可以将函数拉出并添加一个 obj 参数。 In my project, adding methods to the prototype helps me;在我的项目中,向原型添加方法对我有帮助; it doesn't hurt me.它不会伤害我。

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'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM