使用javascript动态推送元素

时间:2017-11-15 05:31:50

标签: javascript

我使用map从多维数组中获取点,但是我得到了数组值数组。

我需要以下格式:

[36, 122, 25]

但是我得到了多点积分。

以下是我的代码和输出



var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]

var result = data.map(function(arr, count) {
  return [arr.points];
});

console.log(result);




输出是:

[[36], [122], [25]]

4 个答案:

答案 0 :(得分:3)

尝试以下代码:

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]          
var result = data.map(function(arr, count) {  return arr.points;});
console.log(result);

答案 1 :(得分:3)



var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
            {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
            {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]          
var result = data.map(function(arr, count) {  return arr.points;});
console.log(result);




从return语句中删除[]。它创建新阵列并将其推送到原始阵列。

答案 2 :(得分:2)

该函数返回单元素数组的数组,因为.map()返回一个数组,并且在.map()的每次迭代中,您的函数返回[arr.points](数组中的元素) 。将此更改为返回arr.points并重新设置。

此外,由于您只是在.map()中返回一个值,我们可以将回调函数简化为:

var result = data.map(arr => arr.points);



var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]
var result = data.map(arr => arr.points);
console.log(result);




答案 3 :(得分:2)

在您的代码中,您使用[]使用arr.points值创建新数组。从return语句中删除[]



var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]
var result = data.map(function(arr, count) {
  return arr.points;
});
console.log(result);