Reputation:
I'm having a little problem with display my array items. I try display from localStorage but don't know how to sort by value so I convert all items into an array then sort it. But now I don't know how to display that array. I tried for
statement and it's only return one object, which mean they stop counting forward for my 'x' to rise. And what it display is only [object Object]
. Anyone has any suggestion?
function loadPlayer() {
const lsOutput = document.getElementById("lsOutput");
var l;
if (localStorage.length < 5) {
l = localStorage.length;
} else {
l = 5;
}
//Sắp xếp localstorage
var listPlayer = [{
playerName: '',
score: ''
}];
for (var i = 0; i < l; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
lsOutput.innerHTML += `${i+1}- ${key}: ${value}<br/>`;
listPlayer.push({
playerName: key,
score: value
});
}
listPlayer.shift();
//Sort array
Array.prototype.sortOnValue = function(key) {
this.sort(function(a, b) {
if (a[key] < b[key]) {
return -1;
} else if (a[key] > b[key]) {
return 1;
}
return 0;
});
}
listPlayer.sortOnValue("score");
console.log(listPlayer);
//const p1Output = document.getElementById("xxxccc");
for (var x = 0; x < listPlayer.length; x++) {
//plOutput.innerHTML = document.writeln(listPlayer[x]);
//plOutput.innerHTML = listPlayer.toString();
document.getElementById("xxxccc").innerHTML = JSON.stringify(listPlayer[x].toString());
}
}
Upvotes: 1
Views: 584
Reputation: 607
remove .toString() its not required.
change the line to
document.getElementById("xxxccc").innerHTML = JSON.stringify(listPlayer[x]);
Upvotes: 0
Reputation: 1833
You need use JSON.stringify for objects:
lsOutput.innerHTML += `${i+1}- ${key}: ${JSON.stringify(value)}<br/>`;
Upvotes: 1