1

I have an array of strings. ["A", "B", "C", "D"]

How can I add a key to the array, to make it object.

Like this, to an array on object.

[{ id: "A" }, { id: "B" }, { id: "C" }]

I tried the following:

const newArray = this.myArray.map(function(item) {
    return 'id:' + item;
 });

This does not work for me though.

1
  • you are returning a string, not an object. Commented Jul 25, 2019 at 18:04

4 Answers 4

6

You're on the right track. You're returning a string. You must return an object

const newArray = this.myArray.map(function(item) {
   return {'id': item};
});
Sign up to request clarification or add additional context in comments.

Comments

3

Inside the map() event handler function you are returning a string not an object. You should form the object and return that.

You can also achieve that in a single line with arrow function (=>):

const myArray = ["A", "B", "C", "D"];
const newArray = myArray.map(i => ({id: i}));
console.log(newArray);

Comments

2

Just return an object instead of a string:

const arr = ["A", "B", "C", "D"];
const res = arr.map(id => ({id}));
console.log(res);

Comments

1

This is a good use-case for Array.prototype.map:

const stringArr = ["A", "B", "C", "D"];

const objArr = stringArr.map(id => ({ id }));

console.log(objArr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.