arunmmanoharan
arunmmanoharan

Reputation: 2675

Convert array to array of objects with key as same as value

how do I convert an array to array of objects with the key being the same as value?

var abc = ["abc", "def"];

var sed = abc.map(function(a, index) {
	return {
  	a: a,
    key: a
  }
})

console.log(sed);

My output should look like

[{
  abc: "abc",
  key: "abc"
 },
 {
 def: "def",
 key: "def"
 }
]

Upvotes: 0

Views: 86

Answers (2)

CRice
CRice

Reputation: 32176

Put brackets around the [a] to turn it into a computed property.

var abc = ["abc", "def"];

var sed = abc.map(function(a, index) {
  return {
    [a]: a,
    key: a
  }
})

console.log(sed);

Upvotes: 3

Giannis Mp
Giannis Mp

Reputation: 1299

You can try this way:

var abc = ["abc", "def"];

var sed = abc.map(function(a, index) {
    var obj = {};
    obj[a] = a;
    obj['key'] = a;
	return obj;
})

console.log(sed);

Upvotes: 0

Related Questions