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,777
  • 9
  • 33
  • 69

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
  • 2,887
  • 1
  • 10
  • 28
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
  • 62,450
  • 9
  • 45
  • 52
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
  • 67,185
  • 15
  • 124
  • 181
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,449
  • 2
  • 20
  • 35