-1

This how the default api returns. I want to sort them with basis of min_conversion_count properties. my initial api return

After sorting the structure changes which is affecting my code. How is it possible to sort them with the property and remain the same format.

Code to sort

    var rewarddata = res1.response.reward_list;
// console.log(rewarddata);
sortable_data = [];

console.log(rewarddata);

for (var idx in rewarddata)
{
    sortable_data.push([idx,rewarddata[idx]]);
    sortable_data.sort(function(a, b) {
        return a[1].min_conversion_count - b[1].min_conversion_count;
    });
    console.log(sortable_data);
  }

After sorting it changes like this. enter image description here

Santosh
  • 3,477
  • 5
  • 37
  • 75
  • What is your question? – Adriano Martins Mar 19 '18 at 21:49
  • i want to sort them with the property I have mentioned with the same format as first screenshot. How do I do that? – Santosh Mar 19 '18 at 21:50
  • 1
    Object keys don't have an inherent order. And it's not the sorting that's changing your data structure, it's that you're explicitly converting objects to arrays. – Daniel Beck Mar 19 '18 at 21:51
  • Objects can't be sorted, only arrays. If you want the items sorted then you'll have to use an array. – bmceldowney Mar 19 '18 at 21:51
  • 1
    In short, you cannot have a sorted object, as it has no definitive concept of property ordering. You can have a sorted array. Fix your other code to work with an array. – fubar Mar 19 '18 at 21:51
  • (Oops, I take it back, times have changed! Object keys [*do* have an inherent order](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key/31102605#31102605), now, turns out.) – Daniel Beck Mar 19 '18 at 21:52
  • so how can I convert my result into object back. – Santosh Mar 19 '18 at 21:52
  • so its not possible to have same format like first screenshot even after the data is sorted ? – Santosh Mar 19 '18 at 21:53

1 Answers1

2

You started out with an object, and you put it into an array in order to sort it; once your array is sorted, you have to turn it back into an object.

const sortedObj = sortable_data.reduce((accum, [key, value]) => {
  accum[key] = value;
  return accum;
}, {});

Note that property ordering is generally not something to rely on. It would be better to save an array of the sorted keys only, and then use that array instead.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320