Related
the fixtures:
{
"new_application" : 1,
"diagnosis_application" : 2,
"details_completion_application" : 3,
"awaiting_treatment_application" : 5,
"closed_application" : 6,
"canceled_application" : 7
}
I need the variables names
You can use Object.keys() to get all the keys from the JSON object.
var jsonObj = {
"new_application" : 1,
"diagnosis_application" : 2,
"details_completion_application" : 3,
"awaiting_treatment_application" : 5,
"closed_application" : 6,
"canceled_application" : 7
}
Object.keys(jsonObj)
Object.keys(jsonObj) will return an array with all the keys:
[
'new_application',
'diagnosis_application',
'details_completion_application',
'awaiting_treatment_application',
'closed_application',
'canceled_application',
]
To get the keys one by one you can use the for-Each loop like this:
Object.keys(jsonObj).forEach(function(key) {
var value = jsonObj[key]; //Gets each key one by one
})
The syntax is for...in, see MDN
const object = { a: 1, b: 2, c: 3 };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// expected output:
// "a: 1"
// "b: 2"
// "c: 3"
I have enum code here.
public enum SCode
{
F101 = 1,
F110 = 2,
F112 = 3,
F153 = 4,
F154 = 5,
F155 = 6,
F156 = 7,
F301 = 8,
F302 = 9,
F303 = 10,
F304 = 11,
F305 = 12,
F306 = 13,
F307 = 14,
F308 = 15,
F309 = 16,
F310 = 17,
F311 = 18,
F319 = 19,
}
I already fix it on number. But I don't need to fix it. I need to use enum as parameter. Can I use like this?
public enum SCode
{
cmd = code,
}
code is the variable that can be change anytime.
Thanks for answer and make me clear.
You cannot provide variables to your enumerations. They have to have a static value. You can provide something like this:
public enum SCode
{
F100, -- its value will be 0
F200 -- its value will be 1
}
or
public enum SCode
{
F100 = 14, -- its value will be 14
F200 -- its value will be 15
}
but you cannot provide a variable like this:
var employeeID = 14;
public enum SCode
{
F100 = employeeID, -- won't work
F200
}
I need to order my list by points, then by positions. How can I order my list by the Positions List property?
public class Sailor
{
public string Name { get; set; }
public int Points { get; set; }
public List<int> Positions { get; set; }
public Sailor(string name, int points, List<int> positions)
{
Name = name;
Points = points;
Positions = positions;
}
}
var sailors = new List<Sailor>
{
new Sailor("Carl", 20, new List<int> { 2, 2, 4, 1, 1 }),
new Sailor("Paul", 10, new List<int> { 4, 5, 3, 2, 5 }),
new Sailor("Anna", 20, new List<int> { 1, 1, 1, 3, 4 }),
new Sailor("Lisa", 11, new List<int> { 3, 4, 5, 5, 2 }),
new Sailor("Otto", 11, new List<int> { 5, 3, 2, 4, 3 })
};
foreach (var sailor in sailors)
{
sailor.Positions.Sort();
}
var orderedListOfSailors = sailors.OrderByDescending(x => x.Points);
This gives me:
Carl, Anna, Lisa, Otto, Paul
What I want it to be:
Anna, Carl, Otto, Lisa, Paul
Why? Because Anna have 3 first places, Carl have 2. Otto have 2, 3, 3, Lisa have 2, 3, 4.
The problem can be solved by using lexicographical odering on instances of Sailor; either you could implement a custom comparator for Sailor or use the ThenBy extension method.
After ordering them by Points, order them again by the number of places.
var orderedListOfSailors = sailors
.OrderByDescending(x => x.Points)
.ThenByDescending(x => x.Positions.Count(y => y == 1))
.ThenByDescending(x => x.Positions.Count(y => y == 2))
.ThenByDescending(x => x.Positions.Count(y => y == 3))
.ThenByDescending(x => x.Positions.Count(y => y == 4));
Say I have a TypeScript enum, MyEnum, as follows:
enum MyEnum {
First,
Second,
Third
}
What would be the best way in TypeScript 0.9.5 to produce an array of the enum values? Example:
var choices: MyEnum[]; // or Array<MyEnum>
choices = MyEnum.GetValues(); // plans for this?
choices = EnumEx.GetValues(MyEnum); // or, how to roll my own?
This is the JavaScript output of that enum:
var MyEnum;
(function (MyEnum) {
MyEnum[MyEnum["First"] = 0] = "First";
MyEnum[MyEnum["Second"] = 1] = "Second";
MyEnum[MyEnum["Third"] = 2] = "Third";
})(MyEnum || (MyEnum = {}));
Which is an object like this:
{
"0": "First",
"1": "Second",
"2": "Third",
"First": 0,
"Second": 1,
"Third": 2
}
Enum Members with String Values
TypeScript 2.4 added the ability for enums to possibly have string enum member values. So it's possible to end up with an enum that look like the following:
enum MyEnum {
First = "First",
Second = 2,
Other = "Second"
}
// compiles to
var MyEnum;
(function (MyEnum) {
MyEnum["First"] = "First";
MyEnum[MyEnum["Second"] = 2] = "Second";
MyEnum["Other"] = "Second";
})(MyEnum || (MyEnum = {}));
Getting Member Names
We can look at the example immediately above to try to figure out how to get the enum members:
{
"2": "Second",
"First": "First",
"Second": 2,
"Other": "Second"
}
Here's what I came up with:
const e = MyEnum as any;
const names = Object.keys(e).filter(k =>
typeof e[k] === "number"
|| e[k] === k
|| e[e[k]]?.toString() !== k
);
Member Values
Once, we have the names, we can loop over them to get the corresponding value by doing:
const values = names.map(k => MyEnum[k]);
Extension Class
I think the best way to do this is to create your own functions (ex. EnumEx.getNames(MyEnum)). You can't add a function to an enum.
class EnumEx {
private constructor() {
}
static getNamesAndValues(e: any) {
return EnumEx.getNames(e).map(n => ({ name: n, value: e[n] as string | number }));
}
static getNames(e: any) {
return Object.keys(e).filter(k =>
typeof e[k] === "number"
|| e[k] === k
|| e[e[k]]?.toString() !== k
);
}
static getValues(e: any) {
return EnumEx.getNames(e).map(n => e[n] as string | number);
}
}
With TypeScript >= 2.4 you can define string enums:
enum Color {
RED = 'Red',
ORANGE = 'Orange',
YELLOW = 'Yellow',
GREEN = 'Green',
BLUE = 'Blue',
INDIGO = 'Indigo',
VIOLET = 'Violet'
}
JavaScript ES5 output:
var Color;
(function (Color) {
Color["RED"] = "Red";
Color["ORANGE"] = "Orange";
Color["YELLOW"] = "Yellow";
Color["GREEN"] = "Green";
Color["BLUE"] = "Blue";
Color["INDIGO"] = "Indigo";
Color["VIOLET"] = "Violet";
})(Color || (Color = {}));
Which is an object like this:
const Color = {
"RED": "Red",
"ORANGE": "Orange",
"YELLOW": "Yellow",
"GREEN": "Green",
"BLUE": "Blue",
"INDIGO": "Indigo",
"VIOLET": "Violet"
}
Thus, in the case of string enums, no need to filter things,
Object.keys(Color) and Object.values(Color) are enough:
const colorKeys = Object.keys(Color) as (keyof typeof Color)[];
console.log('colorKeys =', colorKeys);
// ["RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "INDIGO", "VIOLET"]
const colorValues = Object.values(Color);
console.log('colorValues =', colorValues);
// ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"]
colorKeys.map(colorKey => {
console.log(`color key = ${colorKey}, value = ${Color[colorKey]}`);
});
/*
color key = RED, value = Red
color key = ORANGE, value = Orange
color key = YELLOW, value = Yellow
color key = GREEN, value = Green
color key = BLUE, value = Blue
color key = INDIGO, value = Indigo
color key = VIOLET, value = Violet
*/
See online example on TypeScript playground
There is no concept of RTTI (runtime type information) in TypeScript (think: reflection) so in order to do this, knowledge of the transpiled JavaScript is required. So, assuming TypeScript 0.95:
enum MyEnum {
First, Second, Third
}
becomes:
var MyEnum;
(function(MyEnum) {
MyEnum[MyEnum["First"] = 0] = "First";
MyEnum[MyEnum["Second"] = 1] = "Second";
MyEnum[MyEnum["Third"] = 2] = "Third";
}
So, this is modeled as a regular object in javascript, where MyEnum.0 == "First" and MyEnum.First == 0. So, to enumerate all of the enum names, you need to get all properties that belong to the object and that are also not numbers:
for (var prop in MyEnum) {
if (MyEnum.hasOwnProperty(prop) &&
(isNaN(parseInt(prop)))) {
console.log("name: " + prop);
}
}
Ok, so now I've told you how to do it, I'm allowed to tell you this is a bad idea. You're not writing a managed language, so you can't bring these habits. It's still just plain old JavaScript. If I wanted to use a structure in JavaScript to populate some kind of choices list, I would use a plain old array. An enum is not the right choice here, pun intended. The goal of TypeScript is to generate idiomatic, pretty JavaScript. Using enums in this way does not preserve this goal.
You can add functions to get the names and indices of the enum:
enum MyEnum {
First,
Second,
Third
}
namespace MyEnum {
function isIndex(key):boolean {
const n = ~~Number(key);
return String(n) === key && n >= 0;
}
const _names:string[] = Object
.keys(MyEnum)
.filter(key => !isIndex(key));
const _indices:number[] = Object
.keys(MyEnum)
.filter(key => isIndex(key))
.map(index => Number(index));
export function names():string[] {
return _names;
}
export function indices():number[] {
return _indices;
}
}
console.log("MyEnum names:", MyEnum.names());
// Prints: MyEnum names: ["First", "Second", "Third"]
console.log("MyEnum indices:", MyEnum.indices());
// Prints: MyEnum indices: [0, 1, 2]
Note that you could just export the _names and _indices consts rather than exposing them through an exported function, but because the exported members are members of the enum it is arguably clearer to have them as functions so they are not confused with the actual enum members.
It would be nice if TypeScript generated something like this automatically for all enums.
I used the solution proposed by David Sherret and wrote an npm library you can use named enum-values...
Git: enum-values
// Suppose we have an enum
enum SomeEnum {
VALUE1,
VALUE2,
VALUE3
}
// names will be equal to: ['VALUE1', 'VALUE2', 'VALUE3']
var names = EnumValues.getNames(SomeEnum);
// values will be equal to: [0, 1, 2]
var values = EnumValues.getValues(SomeEnum);
A one-liner to get a list of entries (key-value objects/pairs):
Object.keys(MyEnum).filter(a=>a.match(/^\D/)).map(name=>({name, value: MyEnum[name] as number}));
enum MyEnum {
First, Second, Third, NUM_OF_ENUMS
}
for(int i = 0; i < MyEnum.NUM_OF_ENUMS; ++i) {
// do whatever you need to do.
}
If you want to associate strings values to your enum these methods don't works. To have a generic function you can do :
function listEnum(enumClass) {
var values = [];
for (var key in enumClass) {
values.push(enum[key]);
}
values.length = values.length / 2;
return values;
}
It's works because TypeScript will add keys in first step, and values in second step.
In TypeScript it's:
var listEnums = <T> (enumClass: any): T[]=> {
var values: T[] = [];
for (var key in enumClass) {
values.push(enumClass[key]);
}
values.length = values.length / 2;
return values;
};
var myEnum: TYPE[] = listEnums<TYPE>(TYPE);
joe's answer just made me realize that is much more easier to rely on the first N numeric keys than making more complex testings:
function getEnumMembers(myEnum): string[]
{
let members = []
for(let i:number = 0; true; i++) {
if(myEnum[i] === undefined) break
members.push(myEnum[i])
}
return members
}
enum Colors {
Red, Green, Blue
}
console.log(getEnumMembers(myEnum))
Iterating over an enum
String Enums are best used for this. Here is an example:
// This is a string enum
enum MyEnum {
First = 'First',
Second = 'Second',
Third = 'Third',
}
// An enum is a TS concept
// However his MyEnum compiles to JS object:
// {
// "First": "First",
// "Second": "Second",
// "Third": "Third"
// }
// Therefore we can get the keys in the following manner:
const keysArray = Object.keys(MyEnum);
for (const key of keysArray) {
console.log(key)
}
// [LOG]: "First"
// [LOG]: "Second"
// [LOG]: "Third"
A type-safe solution could be as follows:
enum Color {
Blue = 'blue',
Green = 'green'
}
enum MoreColor {
Yellow,
Red
}
function getEnumValues<T, K extends keyof T>(enumType: T): Array<T[K]> {
return getEnumKeys<T, K>(enumType).map((x) => enumType[x]);
}
function getEnumKeys<T, K extends keyof T>(enumType: T): Array<K> {
return Object.keys(enumType)
.filter((x) => Number.isNaN(Number(x)))
.map((x) => x as K);
}
// return type is Color[]
const colorValues = getEnumValues(Color); // ["blue", "green"]
// return type is MoreColor[]
const moreColorValues = getEnumValues(MoreColor); // [0, 1]
// return type is Array<"Blue" | "Green">
const colorKeys = getEnumKeys(Color); // ["Blue", "Green"]
// return type is Array<"Yellow" | "Red">
const moreColorKeys = getEnumKeys(MoreColor); // ["Yellow", "Red"]
But keep in mind that this solution does not force you to pass just enums to the function.
for nodejs:
const { isNumber } = require('util');
Object.values(EnumObject)
.filter(val => isNumber(val))
.map(val => {
// do your stuff
})
Q1: What is better shorthand version of the following?
Q2: How can I pass anonymous types to my view in mvc3?
public ViewResult Index3()
{
List<T1> ls = new List<T1>();
ls.Add(new T1 { id = 1, title = "t1", val1 = 1, val2 = 2});
ls.Add(new T1 {id=2, title="t2", val1=3, val2=4});
ls.Add(new T1 { id = 3, title = "t3", val1 = 5, val2 = 6});
return View(ls);
}
(Q1) Something similar to?:
List<T1> ls = new List<T1>(
List<T1>(new { id = 1, title = "t1", val1 = 1, val2 = 2}
new { id = 2, title = "t2", val1 = 3, val2 = 4})
);
(Q2) Something similar to?:
public ViewResult Index3()
{
return View(List(new { id = 1, title = "t1", val1 = 1, val2 = 2 }
new { id = 2, title = "t2", val2 = 3, val2 = 4 }
);
}
Then reference the above in the razor view:
#model IEnumerable<Some Anonymous or Dynamic Model>
#item.id
#item.title
#item.val1
...
Q1 is a matter of preference. There is no performance difference as the compiler internally creates similar code.
Q2 is impossible, you must create a non-anonymous type to be able to access it.
Could use ViewBag to pass your list to the view.
Collection initializers are written like this:
List<T1> ls = new List<T1> {
new T1 { id = 1, title = "t1", val1 = 1, val2 = 2 },
new T1 { id = 2, title = "t2", val1 = 3, val2 = 4 },
new T1 { id = 3, title = "t3", val1 = 5, val2 = 6 }
};
Create an implicitly-typed array:
return View(new [] { new { id = 1, ... }, ... });
Neither option will work as anonymous types are internal and razor views are compiled into a separate assembly.
See:
Dynamic view of anonymous type missing member issue - MVC3