Estoy luchando para convertir correctamente el objeto en una matriz agrupada de objetos. ¿Alguna sugerencia de cómo obtener los resultados esperados? La parte más importante es agruparlo por HIGH_PRICE
y LOW_PRICE
y crear matrices de esas claves y valores agrupados, pero sería bueno incluir adicionalmente el nombre de lo que queda de una parte similar de la clave, por ejemplo, si tengo HIGH_PRICE_QQQ
y LOW_PRICE_QQQ
el nombre sería ser QQQ
.
Example of the object to sort: const obj = { HIGH_PRICE_QQQ: "10000", HIGH_PRICE_WWW: "2000", LOW_PRICE_WWW: "200", HIGH_PRICE_EEE: "3000", LOW_PRICE_EEE: "300", }
Expected result: const sorted = [ { name: "QQQ", HIGH_PRICE_QQQ: "10000", }, { name: "WWW", HIGH_PRICE_WWW: "2000", LOW_PRICE_WWW: "200", }, { name: "EEE", HIGH_PRICE_EEE: "3000", LOW_PRICE_EEE: "300", } ]
puede usar reduce
para agrupar por el nombre. Finalmente, para obtener el formato de matriz que desea, use Object.values
en el resultado.
Object.entries
utilizadas para hacer obj
iterable
split
y pop
utilizado para extraer el nombre que es el último elemento de la matriz dividida
const obj = { HIGH_PRICE_QQQ: "10000", HIGH_PRICE_WWW: "2000", LOW_PRICE_WWW: "200", HIGH_PRICE_EEE: "3000", LOW_PRICE_EEE: "300", } let x = Object.values(Object.entries(obj).reduce((acc,[k,v])=> { let name = k.split("_").pop() acc[name]= acc[name] || {name} acc[name][k] = v return acc },{})) console.log(x)
La siguiente puede ser una posible solución para lograr el objetivo deseado.
Fragmento de código
// helper method to extract the "name" const getName = s => ( s.includes("HIGH_PRICE_") ? s.split("HIGH_PRICE_").at(1) : s.includes("LOW_PRICE_") ? s.split("LOW_PRICE_").at(1) : s ); // group the object by name const groupByName = obj => ( Object.values( // extract only values of below result Object.entries(obj) // extract key-value pairs from argument "obj" .reduce( // iterate over key-values to generate intermediate result (fin, [k, v]) => ({ // "fin" is the accumulator / aggregator ...fin, [getName(k)]: ( // "name" is used as the key, and value is constructed [getName(k)] in fin ? {...fin[getName(k)], [k]: v} : { name: getName(k), [k]: v} ) }), {} // "fin" is being set to empty-object at begining ) ) ); const rawObj = { HIGH_PRICE_QQQ: "10000", HIGH_PRICE_WWW: "2000", LOW_PRICE_WWW: "200", HIGH_PRICE_EEE: "3000", LOW_PRICE_EEE: "300", }; console.log(groupByName(rawObj));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Explicación
Los comentarios en línea en el fragmento anterior proporcionan una descripción de los distintos pasos.