1

I need to create a Typescript Object in which a certain element with the key 'NONE' always remains at last. I need this to ensure that while rendering this object in my HTML page its value appears at bottom. So basically I need an implementation of myObject.shiftKeyToLastPosition(keyname);

I've tried deleting and re-appending and reduce method. That didn't help.

1
  • There is no way to do this. In Javascript, objects are unordered lists. To have items in a specific order you must use an Array Commented Oct 5, 2020 at 8:36

2 Answers 2

2

If all your properties are string, you could try this

const source = {
  'Domestic': '1',
  'NONE': '0',
  'Wild': '2',
};

const { NONE, ...dest } = source;
dest.NONE = source.NONE;

console.log(dest);

Here we are creating a new object without the NONE key and then adding NONE key at the last.

As per ECMAScript 2015 spec, the traversal of an object with string keys would yield keys in order of insertion.

P.S: Assuming that you have only integer and string keys, no Symbol keys.

Sign up to request clarification or add additional context in comments.

Comments

2

As pointed out by proxima-b, there's no way to deterministically order an object.

What you can do though, is create an helper function that lets you define the order in which you'd like to display the key/values. The cool thing with Typescript is that you can do that in a type safe way!

const myObject = {
  'hello3': 'Value 3',
  'hello1': 'Value 1',
  'hello2': 'Value 2',
  'hello4': 'Value 4',
} as const;

function orderObjectToArrayKeyValue<Obj>(obj: Obj, orderKeys: { [key in keyof Obj]: number }): { key: keyof Obj, value: Obj[keyof Obj] }[] {
  return Object
    .entries<number>(orderKeys)
    .sort(([, order1], [, order2]) => order1 < order2 ? -1 : 1)
    .map(([key]) => ({ key, value: obj[key as keyof Obj] }) as { key: keyof Obj, value: Obj[keyof Obj] });
}

With the above example, if you call:

console.log(orderObjectToArrayKeyValue(myObject, {
  hello1: 1,
  hello2: 2,
  hello3: 3,
  hello4: 4,
}));

You'll get

[
  {
    "key": "hello1",
    "value": "Value 1"
  },
  {
    "key": "hello2",
    "value": "Value 2"
  },
  {
    "key": "hello3",
    "value": "Value 3"
  },
  {
    "key": "hello4",
    "value": "Value 4"
  }
]

Then using the framework of your choice, it'll be really easy to loop over that array and display the values (+ use the key if needed).

Here's a live example (press enter while focusing the left side and it'll run the code, the output will be displayed in your console).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.