Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
Make arr of objects with the same key javascript

I have arr

let arr = [ 
    {tags: {x: 2, y: 12}}, 
    {type: {x: 23, y: 44}}, 
    {order: {x: 5, y: 1200}}, 
]

and need (the same key, but value must come from current x)

let arr = [ 
  {tags: 2}, 
  {type: 23}, 
  {order: 5} 
] 

what I try

arr.map(({ k, v }) => { [k]: v.x });

Please about help!!

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

This should be one possible way to obtain the desired objective.

Code Snippet

let arr = [ 
    {tags: {x: 2, y: 12}}, 
    {type: {x: 23, y: 44}}, 
    {order: {x: 5, y: 1200}}, 
];

const res = arr.flatMap(
  obj => Object.entries(obj).map(
    ([k, {x}]) => ({ [k]: x })
  )
);

console.log(res);

Explanation

  • Iterate over the array using .flatMap() (to avoid nested-array in the result)
  • Take each object (obj) and iterate over key-value pairs using Object.entries()
  • Now, de-structure the [key, value] iterator to directly access prop x
  • Transform it to an object with x as the value
about 4 years ago · Santiago Gelvez Denunciar

0

let arr = [ 
    {tags: {x: 2, y: 12}}, 
    {type: {x: 23, y: 44}}, 
    {order: {x: 5, y: 1200}}, 
]

arr.map((item) => {
    const newItem = {}
    newItem[ Object.keys(item)[0]] = item[Object.keys(item)[0]].x
    return newItem
})

This is my solution. It's worked but I don't think it is good answer!

about 4 years ago · Santiago Gelvez Denunciar

0

You're moving in the right direction. You just need Object.entries to help you get k and v as an array [k, v].

let arr = [ {tags: {x: 2, y: 12}}, {type: {x: 23, y: 44}}, {order: {x: 5, y: 1200}} ];

const output = arr.flatMap(
  o => Object.entries(o).map(([k,v]) => ({[k]:v.x}))
);
console.log( output );

Alternatively, since v has the same properties in all the elements, you can use destructuring as in the demo below:

let arr = [ {tags: {x: 2, y: 12}}, {type: {x: 23, y: 44}}, {order: {x: 5, y: 1200}} ];

const output = arr.flatMap(
  o => Object.entries(o).map(([k,{x,y}]) => ({[k]:x}))
);
console.log( output );

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda