-2

I have object which also has object as a value. I want to sort that object based on 'copy' key value. fiddle

var x= {'one':{'copy':'b'},'two':{'copy':'v'},'three':{'copy':'a'}}

var getsort= []

for(i in x){
 var a= new Object();
    a[i]=x[i]

    getsort.push(a)
}

getsort.sort(function(a,b){
    //console.log(b)
    //console.log(a.copy)
    var textA = a.copy.toUpperCase();
    var textB = b.copy.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
})
console.log(getsort)
Jitender
  • 7,593
  • 30
  • 104
  • 210

2 Answers2

1

This will work for you:

var x= {'one':{'copy':'b'},'two':{'copy':'v'},'three':{'copy':'a'}}

var getsort= []

for(i in x){
    if (i != undefined)
    {

    //console.log(i);
 var a= new Object();
    a[i]=x[i]
    //console.log(a[i]);
    getsort.push(a);
    }
}


function getValue(data)
{
    for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        return value;
    }
}
}

getsort.sort(function(a,b){
    console.log(getValue(b).copy)
    console.log(getValue(a).copy)
    var textA = getValue(a).copy.toUpperCase();
    var textB = getValue(b).copy.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
})
console.log(getsort);
Kram
  • 526
  • 5
  • 11
-1

No, properties order in objects are not guaranteed in JavaScript, you need to use an Array.

But to make an array you don't need to copy to another object in the loop

  var x= {'one':{'copy':'b'},'two':{'copy':'v'},'three':{'copy':'a'}}

    var getsort= [];

    for (i in x) {  
        getsort.push(x[i])
    }

    getsort.sort(function(a,b){

        var textA = a.copy.toUpperCase();
        var textB = b.copy.toUpperCase();

        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;

    })
    console.log(getsort)
Sarath
  • 9,030
  • 11
  • 51
  • 84