-1

If i have an object say

object1 = {
  a: "val1"
  b: "val2",
  c: "val3",
}

I want to swap properties to get

    object1={
        b:"val2"
        a:"val1",
        c:"val3",
        }

Thanks in advance

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
swati kiran
  • 675
  • 1
  • 4
  • 22

2 Answers2

0

The easiest thing to do is manually rearrange properties:

var object1 = {
  a: "val1",
  b: "val2",
  c: "val3",
}

object1 = {
  b: object1.b,
  a: object1.a,
  c: object1.c,
}

console.log(object1);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

There is no sorting of a JavaScript Object properties and no particular order maintained by existing browser vendors except for that of Microsoft IE+.

This means that you cannot arrange or rearrange object properties at all. The object keys order arbitrary and is not maintained anyhow. It simply is not a language requirement and the keys order maintenance decision is up to implementation party.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26
  • I thought the reverse is true? Browsers that support ES6+ *do* have defined property orders (as described by the spec), but ancient browsers like IE which implement ES5 don't have such a guarantee. (if iteration over properties is reliable in IE, it's purely coincidental) – CertainPerformance Jan 18 '19 at 07:31
  • @CertainPerformance, it actually is not - and factually IE has also a strong array sort, but that's not deliberate - the reliable array sort and property order of IE throughout its history is inherited form the reuse of other ready system modules, most probably not a deliberate. But there it is. – Bekim Bacaj Jan 18 '19 at 07:37
  • See https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order#answer-5525812 and look at the spec: [1](https://www.ecma-international.org/ecma-262/6.0/#sec-enumerableownnames) [2](https://www.ecma-international.org/ecma-262/6.0/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys) The spec seems to disagree `For each own property key P of O that is a String but is not an integer index, in property creation order` – CertainPerformance Jan 18 '19 at 07:42
  • That is the *official Ecmascript specification.*. I was under the impression that there is no higher authority? Why do you think it is "bs"? Honest question, if there is a reason why I should not trust it, I want to know, since I write and look at a lot of Javascript, so I want to be informed. (What should I trust instead?) – CertainPerformance Jan 18 '19 at 07:55
  • are you sick or something ?! – Bekim Bacaj Jan 19 '19 at 11:24