2017-04-03 93 views
-1

我試圖過濾這個數組來獲取id並將字符串轉換爲數字。我想使用過濾器和地圖?想知道如何儘可能清楚。如何在數組上使用array.filter + map

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']}, 
]; 
+0

請添加搜索參數,輸出和你試過了什麼。您也可以在這裏看看:[mcve] –

回答

0

所有你需要的是map靜下心來,一個ID數組作爲數字:

pets = pets.map(function(pet) { 
    return Number(pet.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"]}]; 
 

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

 
console.log(pets);

+0

感謝您的幫助,但是我的11次返回「對象」。這裏是我的代碼 –

+0

函數petSorter(pet){cat_l = cats.map(function(pet){ return Number(pet.id); }); } console.log(cats); –

+0

@JacobJabocJones,查看更完整的代碼示例可能會有所幫助,如果這有助於您可以使用[JSFiddle](https://jsfiddle.net/)。 – KevBot

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

考慮提供解​​釋給你的代碼 – arghtype

相關問題