0

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"
 }
]

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

You can omit the index argument there. Also, this makes a nice one-liner: abc.map(a => ({ [a]: a, key: a })).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.