简体   繁体   中英

I want to swap the elements inside the nested array of objects inside at particular index in javascript?

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

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;
    })

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