将对象数组的特定值转换为字符串

时间:2018-02-08 12:08:43

标签: javascript angularjs

var users = [{
  user_id: 26795,
  social_id: null,
  type: 2,
  sport_id: "1",
  name: "G3 One"
}, {
  user_id: 84854,
  social_id: null,
  type: 2,
  sport_id: "1",
  name: "fd"
}, {
  user_id: 84855,
  social_id: null,
  type: 2,
  sport_id: "1",
  name: "Third Users"
}];

如何将user_id转换为字符串

var strArr = users.map(function(e){
     console.log(e.user_id.toString());
     if(e.user_id) {
         e.user_id.toString();
     }
     return e;
});

user_id值应使用string方法转换为map()

2 个答案:

答案 0 :(得分:0)

var array1 = [{user_id: 26795, social_id: null, type: 2, sport_id: "1", name: "G3 One"},
{user_id: 84854, social_id: null, type: 2, sport_id: "1", name: "fd"},
{user_id: 84855, social_id: null, type: 2, sport_id: "1", name: "Third Users"}];

array1.map(x => x.user_id = x.user_id.toString());
console.log(array1);

Fiddle Link Here

答案 1 :(得分:0)

可以避免使用箭头功能,因为它在旧版浏览器和IE11中不受支持。通过使用回调函数内的返回值,你应该没问题:

> Demo fiddle

var users = [{
  user_id: 26795,
  social_id: null,
  type: 2,
  sport_id: "1",
  name: "G3 One"
}, {
  user_id: 84854,
  social_id: null,
  type: 2,
  sport_id: "1",
  name: "fd"
}, {
  user_id: 84855,
  social_id: null,
  type: 2,
  sport_id: "1",
  name: "Third Users"
}];

users.map(function (item) {
    item.user_id = item.user_id.toString();
    return item;
})

console.log(users);