My data looks like this
data = [
{
"id": "27eb95f9",
"title": "hello",
"sort": 4
},
{
"id": "367da510",
"title": "bro",
"sup-title": "",
"sort": 2
},
{
"id": "27eb95f9",
"title": "how ",
"sort": 3
},
{
"id": "367da510",
"title": "you doing",
"sup-title": "",
"sort": 1
},
Now I want to use map funtion in React to show 'title' but I want the order to be according to "sort" in the object file. How can I do that ?
CodePudding user response:
it may works, first JSON.parse(data) to have it as a object then
data.map(row => return {
...row, order : row.sort
})
CodePudding user response:
First use sort function, then map it! Please see below. In the second exapmle you can use it to render your componenet as well.
Here can you read about sort method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
const data = [
{
"id": "27eb95f9",
"title": "hello",
"sort": 4
},
{
"id": "367da510",
"title": "bro",
"sup-title": "",
"sort": 2
},
{
"id": "27eb95f9",
"title": "how ",
"sort": 3
},
{
"id": "367da510",
"title": "you doing",
"sup-title": "",
"sort": 1
}];
const sortedTitles = data.sort((d1, d2)=>d1-d2).map((d)=>d.title);
console.table(sortedTitles);
render = data.sort((d1, d2)=>d1-d2).map((d)=>`<p>${d.title}</p>`).join("");
console.log(render);
document.getElementById("app").innerHTML = render
<div id="app"></div>