-1

I am trying to create a new object by taking reference of an existing object as done below.

var c = {
        "pstn_id": 1,
        "pstn_ds": 1,
        "pstn_titl_tx": 1,
          "job_id": 1,
           "ov_co_id":1,
          "efcv_bgdt":1

                            };

var newObj ={};
Object.getOwnPropertyNames(c).forEach(function(ce){

  newObj["_"+ce] = "$"+ce;
});
console.log(newObj);
//console
[object Object] {
  _efcv_bgdt: "$efcv_bgdt",
  _job_id: "$job_id",
  _ov_co_id: "$ov_co_id",
  _pstn_ds: "$pstn_ds",
  _pstn_id: "$pstn_id",
  _pstn_titl_tx: "$pstn_titl_tx"
}

This console shows an object but not in the order of the reference object I have used

Why is the newly created property names not in the order of their looping.

I want it in this order,

{
  _pstn_id: "$pstn_id",
  _pstn_ds: "$pstn_ds",
  _pstn_titl_tx: "$pstn_titl_tx",
  _job_id: "$job_id",
  _ov_co_id: "$ov_co_id",
  _efcv_bgdt: "$efcv_bgdt"
}
Sundeep.R
  • 21
  • 1
  • 4
  • Possible duplicate of [How to change the order of the fields in JSON](https://stackoverflow.com/questions/16542529/how-to-change-the-order-of-the-fields-in-json) – Moritz Roessler Oct 10 '18 at 10:33
  • [Objects are an unordered colection of properties](https://stackoverflow.com/a/16542597/1487756). You can use the spread operator to do this as well. `obj2 = {...obj, a:"b"}` – Moritz Roessler Oct 10 '18 at 10:35
  • You are getting in the same order as the older object when you console it but when you click on it to expand and see all values Google chrome arrange it in Ascending Order. – Vishesh Oct 10 '18 at 11:29

1 Answers1

1

What you are looking for is Object.assign. As was mentioned before, an object is an unordered list of key value pairs, so you can't guarantee the order in which they print. If you want to keep insertion order then look at Maps. They might help.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

miguelsolano
  • 519
  • 3
  • 11