Sorting JSON alphabetically
I am trying to output the JSON below to HTML. I ace created an object along with properties for that object, however I am struggling to output it to HTML. Here's what I have so far. Any idea?
var people;
people = [{
first_name: 'Don Molloy',
category: 'academic'
},
{
first_name: 'Pat Quill',
category: 'academic'
}
];
console.log(people);
var myObj = JSON.parse(people);
document.getElementById("output-people").innerHTML = myObj.name;
<p id="output-people"></p>
thank,
source to share
It is not json
Object. has a normal array Object.so deletes JSON.parse()
. And changes the output of innerHTML dom as followsmyObj[0].first_name
Update:
For all first_name sorted by .try this myObj.map(a=> a.first_name).sort().join(" and ")
var people;
people = [{
first_name: 'Don Molloy',
category: 'academic'
},
{
first_name: 'Pat Quill',
category: 'academic'
}
];
people = people.sort((a,b)=> {
var a1 = a.first_name.toLowerCase();
var b1 = b.first_name.toLowerCase();
return a1<b1 ?-1:a1> b1? 1 :0;
})
console.log(people);
var myObj =people;
document.getElementById("output-people").innerHTML = myObj.map(a=> a.first_name).join(" and ")
<p id="output-people"></p>
source to share
For your question "Sorting JSON alphabetically" you can first use Array.prototype.sort () to sort the array and what to fill in the variable output
and also use the separator
way the names are displayed in html.
code:
var output = '',
separator = '<br>',
people = [{first_name: 'Don Molloy',category: 'academic'}, {first_name: 'Pat Quill',category: 'academic'}];
// Sort array of objects by first_name and populate the output
people
.sort(function (a, b) {
// ignore upper and lowercase
var nameA = a.first_name.toUpperCase(),
nameB = b.first_name.toUpperCase();
return nameA < nameB
? -1
: nameA > nameB
? 1
: 0;
})
.forEach(function (el) {
output += el.first_name + separator;
});
console.log(people);
document.getElementById('output-people').innerHTML = output;
<p id="output-people"></p>
Check the correct sorting of the array of objects by the property string:
var arr = [{first_name: 'a'}, {first_name: 'c'}, {first_name: 'b'}];
arr.sort();
console.log(arr);
arr.sort(function (a, b) {
// ignore upper and lowercase
var nameA = a.first_name.toUpperCase(),
nameB = b.first_name.toUpperCase();
return nameA < nameB
? -1
: nameA > nameB
? 1
: 0;
});
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
source to share