Home > Net >  Inserting Elements In Array As an Object but without using keys in Javascript
Inserting Elements In Array As an Object but without using keys in Javascript

Time:03-09

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) 

CodePudding user response:

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,

CodePudding user response:

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);

  • Related