sort Key of JSONArray





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have a json Array like this :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos4": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos2": "free"
}
]


How can i Organize my json to have somethign like that :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos2": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos4": "free"
}
]


Because i need to have 'pos' in progressive order



I hope someone will understand my problem, and tell me how can i can resolve this..



I have already search and not found the same problem than me..
Thanks a lot










share|improve this question























  • keys are not intended to work like that, it is possible and I will help you if that's what you want, but let me ask you first. Can't you just add a key with name: "id": 0, "id": 1, etc? otherwise we will have to strip the digits from the object.key which isn't very beautiful :P

    – joelgullander
    Jan 4 at 0:50











  • Your objects should have a common name for the identifier property.

    – Tiny Giant
    Jan 4 at 0:51











  • I know that these keys are not beautiful, but in my program it make like that... I will try to change it :x

    – Mathieu d.o
    Jan 4 at 0:54


















0















I have a json Array like this :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos4": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos2": "free"
}
]


How can i Organize my json to have somethign like that :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos2": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos4": "free"
}
]


Because i need to have 'pos' in progressive order



I hope someone will understand my problem, and tell me how can i can resolve this..



I have already search and not found the same problem than me..
Thanks a lot










share|improve this question























  • keys are not intended to work like that, it is possible and I will help you if that's what you want, but let me ask you first. Can't you just add a key with name: "id": 0, "id": 1, etc? otherwise we will have to strip the digits from the object.key which isn't very beautiful :P

    – joelgullander
    Jan 4 at 0:50











  • Your objects should have a common name for the identifier property.

    – Tiny Giant
    Jan 4 at 0:51











  • I know that these keys are not beautiful, but in my program it make like that... I will try to change it :x

    – Mathieu d.o
    Jan 4 at 0:54














0












0








0








I have a json Array like this :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos4": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos2": "free"
}
]


How can i Organize my json to have somethign like that :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos2": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos4": "free"
}
]


Because i need to have 'pos' in progressive order



I hope someone will understand my problem, and tell me how can i can resolve this..



I have already search and not found the same problem than me..
Thanks a lot










share|improve this question














I have a json Array like this :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos4": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos2": "free"
}
]


How can i Organize my json to have somethign like that :



[
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos2": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos4": "free"
}
]


Because i need to have 'pos' in progressive order



I hope someone will understand my problem, and tell me how can i can resolve this..



I have already search and not found the same problem than me..
Thanks a lot







javascript json






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 4 at 0:45









Mathieu d.oMathieu d.o

505




505













  • keys are not intended to work like that, it is possible and I will help you if that's what you want, but let me ask you first. Can't you just add a key with name: "id": 0, "id": 1, etc? otherwise we will have to strip the digits from the object.key which isn't very beautiful :P

    – joelgullander
    Jan 4 at 0:50











  • Your objects should have a common name for the identifier property.

    – Tiny Giant
    Jan 4 at 0:51











  • I know that these keys are not beautiful, but in my program it make like that... I will try to change it :x

    – Mathieu d.o
    Jan 4 at 0:54



















  • keys are not intended to work like that, it is possible and I will help you if that's what you want, but let me ask you first. Can't you just add a key with name: "id": 0, "id": 1, etc? otherwise we will have to strip the digits from the object.key which isn't very beautiful :P

    – joelgullander
    Jan 4 at 0:50











  • Your objects should have a common name for the identifier property.

    – Tiny Giant
    Jan 4 at 0:51











  • I know that these keys are not beautiful, but in my program it make like that... I will try to change it :x

    – Mathieu d.o
    Jan 4 at 0:54

















keys are not intended to work like that, it is possible and I will help you if that's what you want, but let me ask you first. Can't you just add a key with name: "id": 0, "id": 1, etc? otherwise we will have to strip the digits from the object.key which isn't very beautiful :P

– joelgullander
Jan 4 at 0:50





keys are not intended to work like that, it is possible and I will help you if that's what you want, but let me ask you first. Can't you just add a key with name: "id": 0, "id": 1, etc? otherwise we will have to strip the digits from the object.key which isn't very beautiful :P

– joelgullander
Jan 4 at 0:50













Your objects should have a common name for the identifier property.

– Tiny Giant
Jan 4 at 0:51





Your objects should have a common name for the identifier property.

– Tiny Giant
Jan 4 at 0:51













I know that these keys are not beautiful, but in my program it make like that... I will try to change it :x

– Mathieu d.o
Jan 4 at 0:54





I know that these keys are not beautiful, but in my program it make like that... I will try to change it :x

– Mathieu d.o
Jan 4 at 0:54












5 Answers
5






active

oldest

votes


















0














A bit late to the party but I don't think the other answers are producing the output you want, i.e. you want to retain the current array order and replace the current pos[num] property of the object in the array with 'pos' + (idx + 1):






const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

const output = input.map((o, idx) => {
const id = Object.keys(o).find(id => /^pos/.test(id));
if (id !== `pos${idx + 1}`) {
o[`pos${idx + 1}`] = o[id];
delete o[id];
}
return o;
});

console.log(output)








share|improve this answer
























  • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json

    – Mathieu d.o
    Jan 4 at 2:41



















0














Assuming that the first property of the object is what you want to sort by, something as simplistic as this should work:






var array = [
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos4": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos2": "free"
}
];

var sortedArray = array.sort((a, b) => {
var nameKeyA = Object.keys(a)[0];
var nameKeyB = Object.keys(b)[0];
return nameKeyA > nameKeyB;
});

console.log(JSON.stringify(sortedArray));








share|improve this answer
























  • Look at the required output again.

    – Andy
    Jan 4 at 0:58











  • @Andy interesting... I figured that was just a typo from OP. I'm not entirely sure why one would want that as the output.

    – Ben Beck
    Jan 4 at 1:01





















0














This will provide you with the output you want. It uses the following JS methods/syntax:




  • map

  • Object.keys()

  • includes

  • Template literals





const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

// Parse the JSON
const arr = JSON.parse(json);

// `map` over the array, grabbing the object and index
const out = arr.map((obj, i) => {

// Iterate over the keys from each object
Object.keys(obj).forEach(key => {

// If a key includes the substring "pos"...
if (key.includes('pos')) {

// ...and the new key number doesn't match the current index...
if (key !== `pos${i + 1}`) {

// ...copy it to a new key (starting at pos1)...
obj[`pos${i + 1}`] = obj[key];

// ...then delete the old key
delete obj[key];

}
}
});

// Return the updated object
return obj;
});

console.log(out);








share|improve this answer


























  • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json :)

    – Mathieu d.o
    Jan 4 at 2:43



















-1














If the name is consistently pos[num] this will work.






let data = [
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos4": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos2": "free"
}
];

const sortPredicate = (a, b) => {

let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

return aProp - bProp;
}

let sortedData = data.sort(sortPredicate);

console.log(sortedData);








share|improve this answer
























  • Please note I agree with the comments above, it would be better to fix the JSON to have a proper key. It looks like you are recording slot allocation and what is in the slot or if its free.

    – Bibberty
    Jan 4 at 0:57



















-1

















let x = [
{
"pos1": "Batterie de préchauffage",
"attributes": [
{
"disconnect": "false",
"disconnectBis": "false"
}
]
},
{
"pos4": "Batterie haute température",
"attributes": [
{
"test": "true",
"testBis": "false"
}
]
},
{
"pos3": "free"
},
{
"pos2": "free"
}
];

function getPosKey(obj) {
const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
return firstMatch;
}

const ordered_keys = x.map(o => getPosKey(o)).sort();
x = x.map((o, idx) => {
const k = getPosKey(o);
if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
delete o[k];
}
return o;
});

console.log(JSON.stringify(x, null, 2));








share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031788%2fsort-key-of-jsonarray%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    A bit late to the party but I don't think the other answers are producing the output you want, i.e. you want to retain the current array order and replace the current pos[num] property of the object in the array with 'pos' + (idx + 1):






    const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

    const output = input.map((o, idx) => {
    const id = Object.keys(o).find(id => /^pos/.test(id));
    if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
    }
    return o;
    });

    console.log(output)








    share|improve this answer
























    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json

      – Mathieu d.o
      Jan 4 at 2:41
















    0














    A bit late to the party but I don't think the other answers are producing the output you want, i.e. you want to retain the current array order and replace the current pos[num] property of the object in the array with 'pos' + (idx + 1):






    const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

    const output = input.map((o, idx) => {
    const id = Object.keys(o).find(id => /^pos/.test(id));
    if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
    }
    return o;
    });

    console.log(output)








    share|improve this answer
























    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json

      – Mathieu d.o
      Jan 4 at 2:41














    0












    0








    0







    A bit late to the party but I don't think the other answers are producing the output you want, i.e. you want to retain the current array order and replace the current pos[num] property of the object in the array with 'pos' + (idx + 1):






    const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

    const output = input.map((o, idx) => {
    const id = Object.keys(o).find(id => /^pos/.test(id));
    if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
    }
    return o;
    });

    console.log(output)








    share|improve this answer













    A bit late to the party but I don't think the other answers are producing the output you want, i.e. you want to retain the current array order and replace the current pos[num] property of the object in the array with 'pos' + (idx + 1):






    const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

    const output = input.map((o, idx) => {
    const id = Object.keys(o).find(id => /^pos/.test(id));
    if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
    }
    return o;
    });

    console.log(output)








    const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

    const output = input.map((o, idx) => {
    const id = Object.keys(o).find(id => /^pos/.test(id));
    if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
    }
    return o;
    });

    console.log(output)





    const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

    const output = input.map((o, idx) => {
    const id = Object.keys(o).find(id => /^pos/.test(id));
    if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
    }
    return o;
    });

    console.log(output)






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 4 at 1:15









    ic3b3rgic3b3rg

    10.9k42045




    10.9k42045













    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json

      – Mathieu d.o
      Jan 4 at 2:41



















    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json

      – Mathieu d.o
      Jan 4 at 2:41

















    it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json

    – Mathieu d.o
    Jan 4 at 2:41





    it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json

    – Mathieu d.o
    Jan 4 at 2:41













    0














    Assuming that the first property of the object is what you want to sort by, something as simplistic as this should work:






    var array = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
    });

    console.log(JSON.stringify(sortedArray));








    share|improve this answer
























    • Look at the required output again.

      – Andy
      Jan 4 at 0:58











    • @Andy interesting... I figured that was just a typo from OP. I'm not entirely sure why one would want that as the output.

      – Ben Beck
      Jan 4 at 1:01


















    0














    Assuming that the first property of the object is what you want to sort by, something as simplistic as this should work:






    var array = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
    });

    console.log(JSON.stringify(sortedArray));








    share|improve this answer
























    • Look at the required output again.

      – Andy
      Jan 4 at 0:58











    • @Andy interesting... I figured that was just a typo from OP. I'm not entirely sure why one would want that as the output.

      – Ben Beck
      Jan 4 at 1:01
















    0












    0








    0







    Assuming that the first property of the object is what you want to sort by, something as simplistic as this should work:






    var array = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
    });

    console.log(JSON.stringify(sortedArray));








    share|improve this answer













    Assuming that the first property of the object is what you want to sort by, something as simplistic as this should work:






    var array = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
    });

    console.log(JSON.stringify(sortedArray));








    var array = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
    });

    console.log(JSON.stringify(sortedArray));





    var array = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
    });

    console.log(JSON.stringify(sortedArray));






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 4 at 0:57









    Ben BeckBen Beck

    1,9731616




    1,9731616













    • Look at the required output again.

      – Andy
      Jan 4 at 0:58











    • @Andy interesting... I figured that was just a typo from OP. I'm not entirely sure why one would want that as the output.

      – Ben Beck
      Jan 4 at 1:01





















    • Look at the required output again.

      – Andy
      Jan 4 at 0:58











    • @Andy interesting... I figured that was just a typo from OP. I'm not entirely sure why one would want that as the output.

      – Ben Beck
      Jan 4 at 1:01



















    Look at the required output again.

    – Andy
    Jan 4 at 0:58





    Look at the required output again.

    – Andy
    Jan 4 at 0:58













    @Andy interesting... I figured that was just a typo from OP. I'm not entirely sure why one would want that as the output.

    – Ben Beck
    Jan 4 at 1:01







    @Andy interesting... I figured that was just a typo from OP. I'm not entirely sure why one would want that as the output.

    – Ben Beck
    Jan 4 at 1:01













    0














    This will provide you with the output you want. It uses the following JS methods/syntax:




    • map

    • Object.keys()

    • includes

    • Template literals





    const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

    // Parse the JSON
    const arr = JSON.parse(json);

    // `map` over the array, grabbing the object and index
    const out = arr.map((obj, i) => {

    // Iterate over the keys from each object
    Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

    // ...and the new key number doesn't match the current index...
    if (key !== `pos${i + 1}`) {

    // ...copy it to a new key (starting at pos1)...
    obj[`pos${i + 1}`] = obj[key];

    // ...then delete the old key
    delete obj[key];

    }
    }
    });

    // Return the updated object
    return obj;
    });

    console.log(out);








    share|improve this answer


























    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json :)

      – Mathieu d.o
      Jan 4 at 2:43
















    0














    This will provide you with the output you want. It uses the following JS methods/syntax:




    • map

    • Object.keys()

    • includes

    • Template literals





    const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

    // Parse the JSON
    const arr = JSON.parse(json);

    // `map` over the array, grabbing the object and index
    const out = arr.map((obj, i) => {

    // Iterate over the keys from each object
    Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

    // ...and the new key number doesn't match the current index...
    if (key !== `pos${i + 1}`) {

    // ...copy it to a new key (starting at pos1)...
    obj[`pos${i + 1}`] = obj[key];

    // ...then delete the old key
    delete obj[key];

    }
    }
    });

    // Return the updated object
    return obj;
    });

    console.log(out);








    share|improve this answer


























    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json :)

      – Mathieu d.o
      Jan 4 at 2:43














    0












    0








    0







    This will provide you with the output you want. It uses the following JS methods/syntax:




    • map

    • Object.keys()

    • includes

    • Template literals





    const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

    // Parse the JSON
    const arr = JSON.parse(json);

    // `map` over the array, grabbing the object and index
    const out = arr.map((obj, i) => {

    // Iterate over the keys from each object
    Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

    // ...and the new key number doesn't match the current index...
    if (key !== `pos${i + 1}`) {

    // ...copy it to a new key (starting at pos1)...
    obj[`pos${i + 1}`] = obj[key];

    // ...then delete the old key
    delete obj[key];

    }
    }
    });

    // Return the updated object
    return obj;
    });

    console.log(out);








    share|improve this answer















    This will provide you with the output you want. It uses the following JS methods/syntax:




    • map

    • Object.keys()

    • includes

    • Template literals





    const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

    // Parse the JSON
    const arr = JSON.parse(json);

    // `map` over the array, grabbing the object and index
    const out = arr.map((obj, i) => {

    // Iterate over the keys from each object
    Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

    // ...and the new key number doesn't match the current index...
    if (key !== `pos${i + 1}`) {

    // ...copy it to a new key (starting at pos1)...
    obj[`pos${i + 1}`] = obj[key];

    // ...then delete the old key
    delete obj[key];

    }
    }
    });

    // Return the updated object
    return obj;
    });

    console.log(out);








    const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

    // Parse the JSON
    const arr = JSON.parse(json);

    // `map` over the array, grabbing the object and index
    const out = arr.map((obj, i) => {

    // Iterate over the keys from each object
    Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

    // ...and the new key number doesn't match the current index...
    if (key !== `pos${i + 1}`) {

    // ...copy it to a new key (starting at pos1)...
    obj[`pos${i + 1}`] = obj[key];

    // ...then delete the old key
    delete obj[key];

    }
    }
    });

    // Return the updated object
    return obj;
    });

    console.log(out);





    const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

    // Parse the JSON
    const arr = JSON.parse(json);

    // `map` over the array, grabbing the object and index
    const out = arr.map((obj, i) => {

    // Iterate over the keys from each object
    Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

    // ...and the new key number doesn't match the current index...
    if (key !== `pos${i + 1}`) {

    // ...copy it to a new key (starting at pos1)...
    obj[`pos${i + 1}`] = obj[key];

    // ...then delete the old key
    delete obj[key];

    }
    }
    });

    // Return the updated object
    return obj;
    });

    console.log(out);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 4 at 1:26

























    answered Jan 4 at 1:21









    AndyAndy

    30.4k73565




    30.4k73565













    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json :)

      – Mathieu d.o
      Jan 4 at 2:43



















    • it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json :)

      – Mathieu d.o
      Jan 4 at 2:43

















    it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json :)

    – Mathieu d.o
    Jan 4 at 2:43





    it's exactly what i want ! thanks a lot, but maybe i will follow your advices, and change my json :)

    – Mathieu d.o
    Jan 4 at 2:43











    -1














    If the name is consistently pos[num] this will work.






    let data = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    const sortPredicate = (a, b) => {

    let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
    let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

    return aProp - bProp;
    }

    let sortedData = data.sort(sortPredicate);

    console.log(sortedData);








    share|improve this answer
























    • Please note I agree with the comments above, it would be better to fix the JSON to have a proper key. It looks like you are recording slot allocation and what is in the slot or if its free.

      – Bibberty
      Jan 4 at 0:57
















    -1














    If the name is consistently pos[num] this will work.






    let data = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    const sortPredicate = (a, b) => {

    let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
    let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

    return aProp - bProp;
    }

    let sortedData = data.sort(sortPredicate);

    console.log(sortedData);








    share|improve this answer
























    • Please note I agree with the comments above, it would be better to fix the JSON to have a proper key. It looks like you are recording slot allocation and what is in the slot or if its free.

      – Bibberty
      Jan 4 at 0:57














    -1












    -1








    -1







    If the name is consistently pos[num] this will work.






    let data = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    const sortPredicate = (a, b) => {

    let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
    let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

    return aProp - bProp;
    }

    let sortedData = data.sort(sortPredicate);

    console.log(sortedData);








    share|improve this answer













    If the name is consistently pos[num] this will work.






    let data = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    const sortPredicate = (a, b) => {

    let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
    let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

    return aProp - bProp;
    }

    let sortedData = data.sort(sortPredicate);

    console.log(sortedData);








    let data = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    const sortPredicate = (a, b) => {

    let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
    let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

    return aProp - bProp;
    }

    let sortedData = data.sort(sortPredicate);

    console.log(sortedData);





    let data = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    const sortPredicate = (a, b) => {

    let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
    let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

    return aProp - bProp;
    }

    let sortedData = data.sort(sortPredicate);

    console.log(sortedData);






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 4 at 0:53









    BibbertyBibberty

    2,3021317




    2,3021317













    • Please note I agree with the comments above, it would be better to fix the JSON to have a proper key. It looks like you are recording slot allocation and what is in the slot or if its free.

      – Bibberty
      Jan 4 at 0:57



















    • Please note I agree with the comments above, it would be better to fix the JSON to have a proper key. It looks like you are recording slot allocation and what is in the slot or if its free.

      – Bibberty
      Jan 4 at 0:57

















    Please note I agree with the comments above, it would be better to fix the JSON to have a proper key. It looks like you are recording slot allocation and what is in the slot or if its free.

    – Bibberty
    Jan 4 at 0:57





    Please note I agree with the comments above, it would be better to fix the JSON to have a proper key. It looks like you are recording slot allocation and what is in the slot or if its free.

    – Bibberty
    Jan 4 at 0:57











    -1

















    let x = [
    {
    "pos1": "Batterie de préchauffage",
    "attributes": [
    {
    "disconnect": "false",
    "disconnectBis": "false"
    }
    ]
    },
    {
    "pos4": "Batterie haute température",
    "attributes": [
    {
    "test": "true",
    "testBis": "false"
    }
    ]
    },
    {
    "pos3": "free"
    },
    {
    "pos2": "free"
    }
    ];

    function getPosKey(obj) {
    const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
    return firstMatch;
    }

    const ordered_keys = x.map(o => getPosKey(o)).sort();
    x = x.map((o, idx) => {
    const k = getPosKey(o);
    if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
    o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
    delete o[k];
    }
    return o;
    });

    console.log(JSON.stringify(x, null, 2));








    share|improve this answer






























      -1

















      let x = [
      {
      "pos1": "Batterie de préchauffage",
      "attributes": [
      {
      "disconnect": "false",
      "disconnectBis": "false"
      }
      ]
      },
      {
      "pos4": "Batterie haute température",
      "attributes": [
      {
      "test": "true",
      "testBis": "false"
      }
      ]
      },
      {
      "pos3": "free"
      },
      {
      "pos2": "free"
      }
      ];

      function getPosKey(obj) {
      const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
      return firstMatch;
      }

      const ordered_keys = x.map(o => getPosKey(o)).sort();
      x = x.map((o, idx) => {
      const k = getPosKey(o);
      if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
      o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
      delete o[k];
      }
      return o;
      });

      console.log(JSON.stringify(x, null, 2));








      share|improve this answer




























        -1












        -1








        -1










        let x = [
        {
        "pos1": "Batterie de préchauffage",
        "attributes": [
        {
        "disconnect": "false",
        "disconnectBis": "false"
        }
        ]
        },
        {
        "pos4": "Batterie haute température",
        "attributes": [
        {
        "test": "true",
        "testBis": "false"
        }
        ]
        },
        {
        "pos3": "free"
        },
        {
        "pos2": "free"
        }
        ];

        function getPosKey(obj) {
        const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
        return firstMatch;
        }

        const ordered_keys = x.map(o => getPosKey(o)).sort();
        x = x.map((o, idx) => {
        const k = getPosKey(o);
        if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
        o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
        delete o[k];
        }
        return o;
        });

        console.log(JSON.stringify(x, null, 2));








        share|improve this answer


















        let x = [
        {
        "pos1": "Batterie de préchauffage",
        "attributes": [
        {
        "disconnect": "false",
        "disconnectBis": "false"
        }
        ]
        },
        {
        "pos4": "Batterie haute température",
        "attributes": [
        {
        "test": "true",
        "testBis": "false"
        }
        ]
        },
        {
        "pos3": "free"
        },
        {
        "pos2": "free"
        }
        ];

        function getPosKey(obj) {
        const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
        return firstMatch;
        }

        const ordered_keys = x.map(o => getPosKey(o)).sort();
        x = x.map((o, idx) => {
        const k = getPosKey(o);
        if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
        o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
        delete o[k];
        }
        return o;
        });

        console.log(JSON.stringify(x, null, 2));








        let x = [
        {
        "pos1": "Batterie de préchauffage",
        "attributes": [
        {
        "disconnect": "false",
        "disconnectBis": "false"
        }
        ]
        },
        {
        "pos4": "Batterie haute température",
        "attributes": [
        {
        "test": "true",
        "testBis": "false"
        }
        ]
        },
        {
        "pos3": "free"
        },
        {
        "pos2": "free"
        }
        ];

        function getPosKey(obj) {
        const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
        return firstMatch;
        }

        const ordered_keys = x.map(o => getPosKey(o)).sort();
        x = x.map((o, idx) => {
        const k = getPosKey(o);
        if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
        o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
        delete o[k];
        }
        return o;
        });

        console.log(JSON.stringify(x, null, 2));





        let x = [
        {
        "pos1": "Batterie de préchauffage",
        "attributes": [
        {
        "disconnect": "false",
        "disconnectBis": "false"
        }
        ]
        },
        {
        "pos4": "Batterie haute température",
        "attributes": [
        {
        "test": "true",
        "testBis": "false"
        }
        ]
        },
        {
        "pos3": "free"
        },
        {
        "pos2": "free"
        }
        ];

        function getPosKey(obj) {
        const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
        return firstMatch;
        }

        const ordered_keys = x.map(o => getPosKey(o)).sort();
        x = x.map((o, idx) => {
        const k = getPosKey(o);
        if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
        o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
        delete o[k];
        }
        return o;
        });

        console.log(JSON.stringify(x, null, 2));






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 4 at 1:15

























        answered Jan 4 at 0:58









        vicatcuvicatcu

        4,06832847




        4,06832847






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031788%2fsort-key-of-jsonarray%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas