-1

I have an array received from backend: ["Drake","Ola","d"], now I need to assign all these values the same key which is id so it looks something like this:

[{id: "Drake"}, {id: "Ola"}, {id: "d"}]

I need a function to do this as the data is gotten after the page has loaded and I have tried many techniques including for loops. I can also use JQuery if necessary, whats the solution please?

Liam
  • 27,717
  • 28
  • 128
  • 190
Olli
  • 512
  • 3
  • 6
  • 22

2 Answers2

0

You could use Array#map and generate single objects with the wanted content.

The map() method creates a new array with the results of calling a provided function on every element in this array.

var data = ["Drake","Ola","d"],
    result = data.map(function (a) { return { id: a }; });

console.log(result);

ES6

var data = ["Drake","Ola","d"],
    result = data.map(a => ({ id: a }));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • please dv, care to comment? – Nina Scholz Oct 18 '16 at 11:16
  • 1
    I guess it was because your original answer was a guess to a bad question. Now OP seems to of clarified this makes more sense. BTW, I didn't downvote – Liam Oct 18 '16 at 11:18
  • @Liam, that's funny, because ["Any answer that gets the asker going in the right direction is helpful ..."](http://stackoverflow.com/help/how-to-answer) – Nina Scholz Oct 18 '16 at 11:26
  • Ha, though you should [never answer an off topic question](http://meta.stackoverflow.com/questions/276572/should-one-advise-on-off-topic-questions) and [questions should be answerable](http://stackoverflow.com/help/dont-ask) :) – Liam Oct 18 '16 at 13:05
0

Map should do the trick. Just create an object for each value with the id property being that value.

var array = ["Drake","Ola","d"];

var newArray = array.map(function(value){
  return {id: value}
})
console.log(newArray);
taguenizy
  • 2,140
  • 1
  • 8
  • 26