0

I have attached the code snippets for java script as following. I want to swap the particular index into the nested array. Following are code snippets for that,

const arr = [
{"ADMIN":[{"id":0,"name":"name"}],"id":"32323"},
{"id":"323","SECURITY NAME":[{"id":1,"name":"name"}]},
{"id":"32","SECURITY A2":[{"id":1,"name":"name"}]}] 

for (let s = 0; s < arr.length; s++) {
      const element =Object.keys(arr[s])[0];
      console.log(typeof element)
    }

I want second and third index of the array like the same one as first one. so inside structure is like first index should Key with array and second will be id.

so final output would be like

const arr = [
{"ADMIN":[{"id":0,"name":"name"}],"id":"32323"},
{"SECURITY NAME":[{"id":1,"name":"name"}],"id":"323"},
{"SECURITY A2":[{"id":1,"name":"name"}],"id":"32"}] 

Thanks

  • Does this answer your question? [Changing the order of the Object keys....](https://stackoverflow.com/questions/6959817/changing-the-order-of-the-object-keys) – kmoser Jun 03 '20 at 17:37
  • Why do you want to do this? Object keys are generally unordered. – kmoser Jun 03 '20 at 17:38
  • Say for example,lets considered the final output.So from this I want to reorder the key name with SECURITY NAME , ADMIN and SECURITY A2. I want in this order and rename key SECURITY A2 with SECURITY A1 – Arunaben Sheth Jun 03 '20 at 17:45

1 Answers1

0

You should not rely on the order of the Object elements because the order of objects is not always guaranteed in JavaScript. Maybe you can give us more information why you want to do that?

To response to your question anyway you could use the sort function and sort the keys of the object and add to a new variable like:

    var newElement = arr.map(a=>{
        var sorted = {}
        Object.keys(a).sort().forEach(el=>{  // instead of sort() you could use reverse()
            sorted[el] = a[el];
        });
        return sorted;
    })
Sheki
  • 1,597
  • 1
  • 14
  • 25
  • Thanks Sheki , could you please tell me one thing also const arr = [ {"ADMIN":[{"id":0,"name":"name"}],"id":"32323"}, {"SECURITY NAME":[{"id":1,"name":"name"}],"id":"323"}, {"SECURITY_A2":[{"id":1,"name":"name"}],"id":"32"}] Here I want to rename the SECURITY_A2 to SECURITY A2 how can I do that ?Thanks in Advance – Arunaben Sheth Jun 03 '20 at 18:36
  • Glad to help! Just check before `sorted[el] = a[el];` like: if(el === "SECURITY_A2"){ sorted["SECURITY A2"] = a[el]; }else{ sorted[el] = a[el]; } – Sheki Jun 04 '20 at 09:09