Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Add key to each value in array

Tags:

javascript

I have this array below that consists of a simple array. What i'm trying to accomplish is to put a key id in front of every array value to achieve something like this ["id:a", "id:b","id:c","id:d"] is there a easy way to accomplish this? any help would be greatly appreciated thank you.

var test = ['a','b','c','d']
like image 381
Best Jeanist Avatar asked Sep 23 '26 01:09

Best Jeanist


1 Answers

You can use .map():

var test = ['a', 'b', 'c', 'd'];

function setID(item, index) {
  var fullname = "id: " + item;
  return fullname;
}

var output = test.map(setID);
console.log(output);
like image 88
Obsidian Age Avatar answered Sep 24 '26 15:09

Obsidian Age



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!