-2

I have the below array

let array= ['shorts', 'tees']

from this I want an array that looks like this

let newArray= [{shorts: []},{tees: []}, ]

can anyone help?

Jegs
  • 579
  • 1
  • 6
  • 14

3 Answers3

4

Just loop over the array with map() and convert each element to the object you want. You can use the syntax [someString] as a property name in an object literal to create that property.

let array = ['shorts', 'tees'];
let newArray = array.map(a => ({ [a]: [] }));
console.log(newArray);
David
  • 208,112
  • 36
  • 198
  • 279
  • worked like a charm mate. I tried the exact same thing earlier but in mine the a was not like [a] as you have done here. Can you help me why this worked and my method just renamed the key of the objects to a? – Jegs Aug 14 '20 at 14:56
  • @Jegs: In JavaScript objects you can refer to a property by its string name using an indexer. So `myObj.prop` is the same as `myObj['prop']`. Using this same syntax in an object literal, `{ prop: 123 }` is the same as `{ ['prop']: 123 }`. – David Aug 14 '20 at 14:59
0

let array= ['shorts', 'tees'];

let result = array.map(elem => ({[elem]: []}));

console.log(result);
Sascha
  • 4,576
  • 3
  • 13
  • 34
0

let array= ['shorts', 'tees']

let list = [];
for(let item of array) {
  let obj = {};
  obj[item] = [];
  list.push(obj)
}
console.log(list)
Edson Magombe
  • 313
  • 2
  • 14