如何在数组上使用array.filter + map

时间:2017-04-03 17:15:02

标签: javascript arrays filter array.prototype.map

我试图过滤此数组以获取ID并将字符串转换为数字。我想使用过滤器和地图?想知道如何让它尽可能清晰。

var pets = [
  { id: '1', name: 'rupert', readyForHome: 'No', age: 12, personality: ['friendly', 'lazy', 'loving']},
  { id: '2', name: 'mrs fluffy', readyForHome: 'Yes', age: 2, personality: ['affectionate', 'playful', 'shy']},
  { id: '3', name: 'tabitha', readyForHome: 'Yes', age: 4, personality: ['aggressive', 'independent']},
  { id: '4', name: 'lily', readyForHome: 'No', age: 8, personality: ['friendly', 'playful', 'mischievous']},
];

2 个答案:

答案 0 :(得分:0)

您需要的只是$('#form').submit(function() { // do something document.form2.submit(); } 以数字形式显示一系列ID:

map

pets = pets.map(function(pet) {
  return Number(pet.id);
});

答案 1 :(得分:0)

var petIds = pets.map(function (pet) {
    petId = parseInt(pet.id);
    return petId;
});