1

I want to move element key3,key 4 in below JavaScript object to first position.

 var JObject=
{
"Key1":Val1,
"Key2":Val2,
"Key3": Val3,
"key4":val4
}

I am expecting output similar like this

var JObject=
{
 "Key3": Val3,
  "key4":val4,
  "Key1":Val1,
  "Key2":Val2,
}

I tried to add json object to array and do unshift as it is dynamic

var data=[];
data.push(JObject);
var stringToFilter = 'Key3';  
data.unshift(data.splice(data.findIndex(item => item.id === stringToFilter), 1)[0])

I am not sure how to get index for 'key3' and unshift it to first

AMDI
  • 895
  • 2
  • 17
  • 40
  • 2
    Keys in JS objects are not explicitly ordered. You will have to use a Map or an array as your data structure. – Đinh Carabus Sep 25 '20 at 09:05
  • 1
    If you use an array here is a function you can use to to move an element from one position to another: https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another – Đinh Carabus Sep 25 '20 at 09:15

2 Answers2

0

To order it, one option is to save your data as an array.

var JObject= [];
JObject[0] = Val3;
JObject[1] = Val4;
JObject[2] = Val1;
JObject[3] = Val2;

or if you need to "convert" it, the easiest way is to use a buffer variable and rearrange the array. - or even use the buffer to continue with your program. (only for static, incomplexe use!)

var JObject= [];
    JObject[0] = Val1;
    JObject[1] = Val2;
    JObject[2] = Val3;
    JObject[3] = Val4;

var buffer;
buffer = JObject;

JObject[0] = buffer[3];
JObject[1] = buffer[4];
JObject[2] = buffer[1];
JObject[3] = buffer[2];
xKean
  • 94
  • 6
0

You could transform the object to array of key-value pairs using Object.entries(), swap that pairs, and transform back to object using Object.fromEntries()

const JObject = {
  Key1: "Val1",
  Key2: "Val2",
  Key3: "Val3",
  Key4: "Val4",
}

const temp = Object.entries(JObject)

const swap = (arr, i, j) => {
  ;[arr[i], arr[j]] = [arr[j], arr[i]]
}

swap(temp, 0, 2)
swap(temp, 1, 3)

const newJObject = Object.fromEntries(temp)

console.log(newJObject)
hgb123
  • 13,869
  • 3
  • 20
  • 38
  • -Thanks for suggestion. How do i convert back to swapped temp array back to JObject with same structure but the item to first – AMDI Sep 25 '20 at 10:08
  • @AMDI you could copy temp to a different array – hgb123 Sep 25 '20 at 10:15
  • @hgb123- I want the temp to be converted back to json object with the changed order of elements – AMDI Sep 25 '20 at 14:03