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

205
Vistas
Inserting Elements In Array As an Object but without using keys in Javascript

Current Situation :

[{
   "Severity":1,
   "Name":"Yash"
 }, {
   "Severity":2,
   "Name":"Yashaswi"
}]

Desired Situation :

[{1: "Yash"}, {2: "Yashaswi"}]

Code being used :

widTags = ["Severity","Name"];
let tempobj = {};
for(let key in widTags) {
  tempobj[key]=prop;    
}
dataArrayWid.push(tempobj) 
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This solution does what you're suggesting without changing the syntax too much from your original code:

const original = [
  {"Severity":1, "Name":"Yash"},
  {"Severity":2, "Name":"Yashaswi"}
];
const final = [];

for (const oldObj of original){ // (Prefer `for...of` to iterate Arrays)
  const
    newObj = {},
    key = oldObj["Severity"],
    val = oldObj["Name"];
  newObj[key] = val; // Uses Severity val as prop name & Name val as prop val
  final.push(newObj);
}
console.log(final);


And this is a more concise version:

const
  original = [ {"Severity":1, "Name":"Yash"}, {"Severity":2, "Name":"Yashaswi"} ],
  final = original.map(obj => ( { [obj.Severity]: obj.Name } ));
console.log(final);

(Here, the .map method of Arrays makes a new Array with each element modified by a function -- in this case an Arrow function).

Note:

  • The extra parentheses tell JavaScript that their contents are an expression containing our Object literal to be returned, not a block of code statements.
  • Similarly, the extra brackets in the Object literal tell JavaScript that their contents are an expression specifying a computed property name, not a static property name,
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can achieve that by using Array.map() method.

Demo :

const dataArrayWid = [{
   "Severity":1,
   "Name":"Yash"
 }, {
   "Severity":2,
   "Name":"Yashaswi"
}];

const result = dataArrayWid.map((obj) => {
    return {
    [obj.Severity]: obj.Name
  }
});

console.log(result);

about 4 years ago · Juan Pablo Isaza 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