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']
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']
Share
Improve this question
asked Jul 17, 2018 at 2:05
Best JeanistBest Jeanist
1,1294 gold badges14 silver badges36 bronze badges
3
|
6 Answers
Reset to default 7You 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);
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);
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);
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)
As @klugjo says use map, like this:
var array1 = ['a','b','c','d'];
const map1 = array1.map(x => 'id:' + x);
console.log(map1);
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;
"id:"
in front of each of your elements and iterate through. Although exactly what is this to be used for? It doesn't seem all that helpful. Seems like your intending to want to make this an object with keys rather than an array of strings. – Spencer Wieczorek Commented Jul 17, 2018 at 2:10