最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Add key to each value in array - Stack Overflow

programmeradmin1浏览0评论

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
  • use map – klugjo Commented Jul 17, 2018 at 2:07
  • 1 You can just add "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
  • use map like this: text.map( x=> "id:"+x), look for browser support. – PresidentPratik Commented Jul 17, 2018 at 2:11
Add a comment  | 

6 Answers 6

Reset to default 7

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

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;

发布评论

评论列表(0)

  1. 暂无评论