Tengo la siguiente salida:
{
"data": {
"title": "Movie 4",
"data": [
{
"userId": 2,
"profile": { "profileImage": "image" },
"round": 1,
},
{
"userId": 4,
"profile": { "profileImage": "image" },
"round":6,
},
{
"userId": 10,
"profile": { "profileImage": "image" },
"round": 4,
},
]
}
}
El resultado que espero es el siguiente:
{
"data": {
"title": "Movie 4",
"data": [
{
"userId": 2,
"profile": { "profileImage": "image" },
"round": 1,
},
{
"userId": 10,
"profile": { "profileImage": "image" },
"round": 4,
},
{
"userId": 4,
"profile": { "profileImage": "image" },
"round":6,
},
]
}
}
Quiero ordenar mi salida por mi round de valores anidados.
Aquí es donde estoy recopilando todos los datos, pero no sé cómo ordenarlos:
let combinedResult = {
title: combinations["data"]["title"],
data: galleryData.map((item, i) => {
let combination = combinations["data"]["eventdata"].find(c => c.partner === item.userId);
return { ...item, round: combination.round, roundStart: combination.roundStart, roundEnd: combination.roundEnd}
})
};
Ya intenté ordenar antes de la return con esto pero no funcionó:
const sorted = Object.entries(resultAfter)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
Puede usar sortBy desde lodash .
import { sortBy } from "lodash";
const sortedData = sortBy(movie.data.data, "round");
Pruébelo en código sandbox .
Otra opción es usar el método sort()
let json = {
"data": {
"title": "Movie 4",
"data": [
{
"userId": 2,
"profile": { "profileImage": "image" },
"round": 1,
},
{
"userId": 4,
"profile": { "profileImage": "image" },
"round":6,
},
{
"userId": 10,
"profile": { "profileImage": "image" },
"round": 4,
},
]
}
}
json.data.data.sort((a,b) => a.round - b.round)
console.log(json)
Simplemente puede ordenar la matriz dentro de los datos del objeto. De esta manera, está editando la misma matriz dentro de los datos del objeto, sort () es un método destructivo que no crea una copia sino que modifica la matriz original
let yourData = {
"data": {
"title": "Movie 4",
"data": [
{
"userId": 2,
"profile": { "profileImage": "image" },
"round": 1,
},
{
"userId": 4,
"profile": { "profileImage": "image" },
"round":6,
},
{
"userId": 10,
"profile": { "profileImage": "image" },
"round": 4,
},
]
}
}
let arrayData = yourData.data.data;
let result = arrayData.sort(compareFunction);
console.log(yourData);
function compareFunction(keyA,keyB){
return keyA.round-keyB.round;
}