Best Jeanist
Best Jeanist

Reputation: 1129

JavaScript Add key to each value in array

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']

Upvotes: 3

Views: 18464

Answers (6)

Biaspoint
Biaspoint

Reputation: 575

Unable to edit @ObsidianAge answer, so minor change:

If you need in the form that the OP asked (Array of objects)

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

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

var output = test.map(setID);
console.log(output);

Upvotes: 2

Axel
Axel

Reputation: 5111

Use Array.from! It's really simple and faster.

var test = ['a', 'b', 'c', 'd'];
var newTest = Array.from(test, val => 'id: '+ val);
console.log(newTest);

Upvotes: 4

vol7ron
vol7ron

Reputation: 42099

Just iterate over the array using forEach and set the value:

var test = ['a','b','c','d']
test.forEach((v,i,arr)=>arr[i]=`id:${v}`)

console.log(test)

Of course a standard for loop works as well:

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

for ( var i=0, n=test.length; i<n; i++){
   test[i] = 'id:' + test[i]
}

console.log(test)

Upvotes: 1

gavgrif
gavgrif

Reputation: 15499

Using map to create a new array and simply prepend the "id: " to the string,

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

var newTest = test.map(function(item){return 'id:' +item})

console.log(newTest); // gives ["id": "a","id": "b","id": "c","id": "d"];

console.log(newTest[1]); // gives 1d: b;

Upvotes: 0

D. Mayen
D. Mayen

Reputation: 464

As @klugjo says use map, like this:

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

const map1 = array1.map(x => 'id:' + x);

console.log(map1);

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

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);

Upvotes: 7

Related Questions