anthnyprschka
anthnyprschka

Reputation: 301

How to create an object with properties named by an array's elements

While

let Adam = {}; 
{Adam}
// { Adam: {} }

the same is not happening for an array of objects:

let Adam = {}; 
let Eva = {}; 
[Adam, Eva].map(man => ({man}))
// [ { man: {} }, { man: {} } ]

I would like to have [{ Adam: {}, Eva: {} }]. Why is this not the case?

Upvotes: 0

Views: 66

Answers (5)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27202

let Adam = {}; 
let Eva = {}; 

let arr = [{}];

arr[0]["Adam"] = Adam;
arr[0]["Eva"] = Eva;

console.log(arr);

Upvotes: 0

frodo2975
frodo2975

Reputation: 11745

What you're looking to do isn't possible programmatically because you're relying on your variable names to create the properties, and in your map function, the variable name is just man.

The only way you can create an array like this is by manually specifying each element:

const arr = [{Adam}, {Eva}]

What you have won't work dynamically, each object would need a name or id property.

Upvotes: 1

Josh Alexy
Josh Alexy

Reputation: 411

Because as it is, when you use the object property shorthand, it takes the name man literally and overwrites that object property name for every iteration of the loop.

Since what you've requested is an array with one object inside, with each of the names nested inside of that object, it would look something like this:

const peopleObject = ["Adam", "Eva"].reduce((accumulatorObject, person) => {
  accumulatorObject[person] = {};
  return accumulatorObject;
}, {});

console.log(peopleObject);
// { Adam: {}, Eva: {} }

const peopleObjectInArray = [peopleObject];
console.log(peopleObjectInArray);
// [ { Adam: {}, Eva: {} } ]

Upvotes: 0

Ele
Ele

Reputation: 33726

I don't know the purpose of this, but you can do this:

let Adam = {}; 
let Eva = {}; 
console.log([{Adam, Eva}])

Another alternative is using the function reduce.

let Adam = {};
let Eva = {};

var result = [[{Adam}, {Eva}].reduce((a, c) => {
  Object.keys(c).forEach(k => (a[k] = c[k]));
  return a;
}, {})];

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Artur P.
Artur P.

Reputation: 896

let Adam = {}; 
let Eva = {};

const arr = [{Adam, Eva}];

Upvotes: 0

Related Questions