'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']
Solution 1:[1]
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);
Solution 2:[2]
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)
Solution 3:[3]
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);
Solution 4:[4]
As @klugjo says use map, like this:
var array1 = ['a','b','c','d'];
const map1 = array1.map(x => 'id:' + x);
console.log(map1);
Solution 5:[5]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Axel |
| Solution 2 | |
| Solution 3 | Biaspoint |
| Solution 4 | D. Mayen |
| Solution 5 |
