Tengo la siguiente matriz de objetos:
const values = [ { clientType: "Client Type 1", value: 130 }, { clientType: "Client Type 2", value: 10 }, { clientType: "Client Type 3", value: -80 }, { clientType: "Client Type 4", value: -52 } ]Quiero "mapear" esta matriz y obtener como resultado el siguiente objeto:
results = { "Client Type 1": 130, "Client Type 2": 10, "Client Type 3": -80, "Client Type 4": -52, }¿Hay alguna manera de hacer esto directamente? (Usando solo una función de mapa)
AIT
const values = [ { clientType: "Client Type 1", value: 130 }, { clientType: "Client Type 2", value: 10 }, { clientType: "Client Type 3", value: -80 }, { clientType: "Client Type 4", value: -52 } ] const result = values.reduce((acc, {clientType, value}) => ({ ...acc, [clientType]: value}), {}) console.log(result)Esta es una pregunta/tarea bastante simple, así que intentaré publicar una respuesta simple y fácil de entender.
const values = [{ clientType: "Client Type 1", value: 130 }, { clientType: "Client Type 2", value: 10 }, { clientType: "Client Type 3", value: -80 }, { clientType: "Client Type 4", value: -52 } ], // loop through "values" object and construct and object the way the OP needs then return it. resultObj = values.reduce((a, c) => { // a: is the object that we are constructing, its default value is {} (empty object) // c: is the current object from the "values" array a[c.clientType] = c.value; return a; }, {}); // this line is not needed, it just prints the result to the console console.log(resultObj);Solo una nota al margen (pero bastante importante), la única forma de acceder a un atributo en el objeto resultante es usar la notación de corchetes:
resultObj['Client Type 1'] // prints: 130
Obtén más información sobre el método de
reduceen MDN.
Este código parece funcionar:
const values = [ { clientType: "Client Type 1", value: 130 }, { clientType: "Client Type 2", value: 10 }, { clientType: "Client Type 3", value: -80 }, { clientType: "Client Type 4", value: -52 } ] values.map(getFull); function getFull(item) { return [item.clientType,item.value].join(" "); }