在javascript数组的每个项目中添加一个字符串前缀

时间:2018-08-26 18:35:48

标签: javascript

我有一个如下数组:

 var arrItems = [
  {id: '1', value: 'table', price: 100},
  {id: '2', value: 'chair', price: 200},
  {id: '3', value: 'bed', price: 300},
];

如何在数组中每个项目的ID中添加字符串'AB'前缀? 我的结果数组应该是:

 var arrItems = [
      {id: 'AB1', value: 'table', price: 100},
      {id: 'AB2', value: 'chair', price: 200},
      {id: 'AB3', value: 'bed', price: 300},
    ];

我可以在地图功能中使用Javascript实现吗?

2 个答案:

答案 0 :(得分:1)

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

我还使用Spread syntax复制了集合的对象并简化了属性更改。

var arrItems = [
  {id: '1', value: 'table', price: 100},
  {id: '2', value: 'chair', price: 200},
  {id: '3', value: 'bed', price: 300},
];

var result = arrItems.map(i => ({...i, id: 'AB' + i.id }))

console.log(result)

答案 1 :(得分:0)

您可以遍历数组并更改该数组中每个对象的值:

var arrItems = [
  {id: '1', value: 'table', price: 100},
  {id: '2', value: 'chair', price: 200},
  {id: '3', value: 'bed', price: 300},
];
// loop through the array and concatenate 'AB' to the id of each object in that array
arrItems.forEach(function(el) {
  el.id = 'AB' + el.id;
});
// just for the demo purpose, we'll log the array in the console
var output = 'Result:\n';
arrItems.forEach(function(el) {
  output += 'id: ' + el.id + ', value: ' + el.value + ', price: ' + el.price +'\n';
});
console.log(output);

希望我进一步推动了你。