简体   繁体   中英

How to move element position in Javascript object

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

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];

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM