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.

user2281858
  • 1,957
  • 10
  • 41
  • 82

4 Answers4

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};
});
silencedogood
  • 3,209
  • 1
  • 11
  • 36
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);
Mamun
  • 66,969
  • 9
  • 47
  • 59
2

Just return an object instead of a string:

const arr = ["A", "B", "C", "D"];
const res = arr.map(id => ({id}));
console.log(res);
baao
  • 71,625
  • 17
  • 143
  • 203
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);
Tom O.
  • 5,730
  • 2
  • 21
  • 35