Sorting JSON Attribute by Name
Question

Hello all :-)


I'm trying to sort specific json by the attribute names.

So if i have: {"name":"John", "age":30, "car":null}

i want it to be returned as:{"age":30,  "car":null, "name":"John"}.


Anyone have done it before?

Do we have any forge component that can help with it?


Thanks,

Maayan

Hi,

What is the purpose and why you want to achieve by doing this formatting in json, could you please provide little more details.

regards

Hello

I thing you can do this by JavaScript,

You need to pass your Json object to  Your JavaScript Via Input parameter -

check this code snippet, you can use this 

function compareStrings(a, b)

 {  

a = a.toLowerCase();

  b = b.toLowerCase();

  return (a < b) ? -1 : (a > b) ? 1 : 0;

}

places.sort(function(a, b) {  

return compareStrings(a.city, b.city);

})


Another way - 

var items = [

  { name: 'Edward', value: 21 },

  { name: 'Sharpe', value: 37 },

  { name: 'And', value: 45 },

  { name: 'The', value: -12 },

  { name: 'Magnetic', value: 13 },

  { name: 'Zeros', value: 37 }

];


// sort by value

items.sort(function (a, b) {

  return a.value - b.value;

});


// sort by name

items.sort(function(a, b) {

  var nameA = a.name.toUpperCase(); // ignore upper and lowercase

  var nameB = b.name.toUpperCase(); // ignore upper and lowercase

  if (nameA < nameB) {

    return -1;

  }

  if (nameA > nameB) {

    return 1;

  }


  // names must be equal

  return 0;

});


I hope this helps 

Thanks

Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.