I have this object:
var fields = {
g8fdfc8: {
label: 'Email',
logic: []
},
ac1200: {
label: 'Age',
logic: []
}
}
I want to move for example key and value up "ac1200", so the result should be like this:
var fields = {
ac1200: {
label: 'Age',
logic: []
}
g8fdfc8: {
label: 'Email',
logic: []
},
}
Wonder if this can be accomplished.
I can’t find a solution even with ChatGPT.
EDIT: Basicly i am building a VUE form editor but the app was written in jquery, that json format is like that.
So i have 2 buttons, one to move a item(field) up inside the fields object.
one to move down.
4
Answers
Your fields would have to be an array. The order of object keys cannot be sorted.
Now, you can use the
splice
method to move theac1200
item up by by 1.Avoid using object as hash arrays, use usual arrays with
id
fields. Objects are more difficult to handle than arrays (arrays have a bunch of methods for manipulating/transforming).Anyway, a generic approach would be
Here we sort the keys alphabetically:
If you want to change an object in-place delete fields first so they would be added to the end in sorted order: