简体   繁体   English

如何在对象的开头添加元素

[英]How to add an element at first of object

I have an object: 我有一个对象:

TICKET_PRIORITIES: {
    LOW: 'low',
    NORMAL: 'normal',
    HIGH: 'high',
    VERY_HIGH: 'very high'
}

In client side I have to add select at first. 在客户端,我必须首先添加select。

Result I wanted to be 结果我想成为

TICKET_PRIORITIES: {
    SELECT: 'select',    
    LOW: 'low',
    NORMAL: 'normal',
    HIGH: 'high',
    VERY_HIGH: 'very high'
}


<select ng-model="selectedPriority" ng-options="key as key | translate for (key, value) in priorities" class="form-control m-b"> </select> 

In this select I wanna select "select" option and select option should be at the first of drop down. 在此选择中,我要选择“选择”选项,而选择选项应位于下拉菜单的第一个。

var TICKET_PRIORITIES = {
    LOW: 'low',
    NORMAL: 'normal',
    HIGH: 'high',
    VERY_HIGH: 'very high'
  };
TICKET_PRIORITIES['SELECT']='select';
alert(JSON.stringify(TICKET_PRIORITIES));  

Demo 演示版

Object properties order are not concerned while creating object but you can create new properties like: 创建对象时不考虑对象属性的顺序,但是您可以创建新的属性,例如:

TICKET_PRIORITIES = {
    LOW: 'low',
    NORMAL: 'normal',
    HIGH: 'high',
    VERY_HIGH: 'very high'
  }

TICKET_PRIORITIES.SELECT='select';

This is not possible . 这是不可能的 Javascript does not care about or enforce the order of properties in objects (see this question for reference). Javascript不在乎或强制对象中属性的顺序(请参阅此问题以供参考)。 Or, to quote the ECMAscript standard (emphasis mine): 或者,引用ECMAscript标准(强调我的意思):

4.3.3 Object An object is a member of the type Object. 4.3.3对象对象是对象类型的成员。 It is an unordered collection of properties each of which contains a primitive value, object, or function. 它是属性无序集合,每个属性都包含原始值,对象或函数。 A function stored in a property of an object is called a method. 存储在对象属性中的函数称为方法。

If order is important to you, you will need a different data structure using arrays, eg something like this: 如果顺序对您很重要,则您将需要使用数组的其他数据结构,例如:

TICKET_PRIORITIES: [
    {id: "LOW", label: "low"},
    {id: "NORMAL", label: "normal"},
    {id: "HIGH", label: "high"},
    {id: "VERY_HIGH", label: "very high"}
]

This allows you to do something like this ( unshift adds an element to the beginng of an array): 这使您可以执行以下操作( unshift将元素添加到数组的开头):

TICKET_PRIORITIES.unshift({id: "SELECT", label: "select"})

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

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