2

I want an object like

var obj = {
    "ABC" : { name: true, dob: true},
    "CDE" : { name: true, dob: true},
    "EFG" : { name: true, dob: true},
    "CBA" : { name: true, dob: true},
    "XYZ" : { name: true, dob: true},
}

currently I have only array of

var arr = ["ABC","CDE","EFG","CBA","XYZ"];

I have tried adding this with

newArray.push({
    key: arr[i],
    name: true,
    dob: true
});

var newObj = {}

newObj[i] = newArray;

but I am not able to pass this as an whole object to my code. when I stringify this it returns

output

{
    '0':"[{
        key: "ABC",
        name: true,
        dob: true
    },{
        key: "CDE",
        name: true,
        dob: true
    }]"
}
Kirankumar Dafda
  • 2,354
  • 5
  • 29
  • 56

4 Answers4

4

You can use Object.assign to create an object. Use spread operator and map to reiterate the array.

var arr = ["ABC", "CDE", "EFG", "CBA", "XYZ"];

var obj = Object.assign(...arr.map(o => ({[o]: {name: true,dob: true}})));
console.log(obj);

Another option is using reduce to convert the array into a valid object.

var arr = ["ABC", "CDE", "EFG", "CBA", "XYZ"];
var obj = arr.reduce((c, v) => Object.assign(c, {[v]: {name: true,dob: true}}), {});

console.log(obj);
Eddie
  • 26,593
  • 6
  • 36
  • 58
1

use Array.reduce

var arr = ["ABC","CDE","EFG","CBA","XYZ"];

var result = arr.reduce((a,c) => {
a[c] = {name: true, dob: true};
return a;
}, {});

console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

var arr = ["ABC","CDE","EFG","CBA","XYZ"];

let obj = {};

arr.forEach(x=> {
  obj[x] = {
    name: true,
    dob: true
  }  
});

console.log(obj)

Loop thru the array, for each of the element, use it as key and add an object as the value

Isaac
  • 12,042
  • 16
  • 52
  • 116
0

This is another way in generating that output Object using JSON.parse()

var objStr = '{'
var arr = ["ABC", "CDE", "EFG", "CBA", "XYZ"], 
    propertyValue = ':{"name":true,"dob":true}'

  for (var x in arr) {
   if (x < arr.length - 1)
    objStr += '"' + arr[x] + '"' + propertyValue + ','
   else
    objStr += '"' + arr[x] + '"' + propertyValue
  }
  objStr += '}'

  
console.log(JSON.parse(objStr))

Hope this help you :)

Bharath
  • 335
  • 2
  • 8