Search code examples
javascriptarraysjsonobjectobject-literal

How can this javascript object be reconstructed


I have an object type as below:

{
"1": {
    "ref": "1",
    "active": "1",
    "showorder": "1",
    "title": "Test 1"
},
"2": {
    "ref": "2",
    "active": "1",
    "showorder": "2",
    "title": "Test 2"
},
"3": {
    "ref": "3",
    "active": "1",
    "showorder": "4",
    "title": "Test 4"
},
"4": {
    "ref": "4",
    "active": "1",
    "showorder": "9",
    "title": "Test 9"
},
"5": {
    "ref": "5",
    "active": "1",
    "showorder": "7",
    "title": "Test 7"
}
}

On the basis of showorder property i need it to be arranged as follows:

{
"1": {
    "ref": "1",
    "active": "1",
    "showorder": "1",
    "title": "Test 1"
},
"2": {
    "ref": "2",
    "active": "1",
    "showorder": "2",
    "title": "Test 2"
},
"3": {
    "ref": "3",
    "active": "1",
    "showorder": "3",
    "title": "Test 3"
},
"4": {
    "ref": "4",
    "active": "1",
    "showorder": "4",
    "title": "Test 4"
},
"5": {
    "ref": "5",
    "active": "1",
    "showorder": "5",
    "title": "Test 5"
}
}

And here is my failed attempt thought i would pass the object to this function :

function reArrangeTilesObject(tilesObj){
var newObj = [];
for(var i in tilesObj){
    var j = 1;
    if(j == tilesObj[i].showorder){
        newObj.push(tilesObj[i]);
        j++;
    }           
}
return newObj;
}

Sorry if i am being unclear. The object is created in a random manner. So what i want is the object to be arranged as per the showorder property. so if showorder is 4 it should come in the key of 4 and not have the object of showorder 9. showorder 9 should come under the key of 9. Thanks


Solution

  • Steps:

    1. Convert the object to an array (objects are unordered, arrays are ordered)
    2. Sort the array

    Code:

    function reArrangeTilesObject(tilesObj) {
        var tilesArray = [];
    
        // Step 1 - convert to array
    
        for (var i in tilesObj) {
            tilesArray.push(tilesObj[i]);
        }
    
        // Step 2 - sort
    
        tilesArray.sort(function(a, b) {
            return a.showorder - b.showorder;
        });
    
        return tilesArray;
    }
    

    Result – an ordered array:

    [
        {"ref":"1","active":"1","showorder":"1","title":"Test 1"},
        {"ref":"2","active":"1","showorder":"2","title":"Test 2"},
        {"ref":"3","active":"1","showorder":"4","title":"Test 4"},
        {"ref":"5","active":"1","showorder":"7","title":"Test 7"},
        {"ref":"4","active":"1","showorder":"9","title":"Test 9"}
    ]