Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda