我有一個如下所示的數據數組。我想選擇x === 1和name ===「Dog」的對象,然後將它們推送到一個新的數組中。 arr2是我期待的結果。感謝你的幫助!在條件數組中選擇對象並生成新數組javascript
var arr1 = [
{y:2.5, x:1, name: "Dog"},
{y:2.7, x:1, name: "Dog"},
{y:2.7, x:1, name: "Dog"},
{y:3.1, x:1, name: "Dog"},
{y:2.7, x:2, name: "Dog"},
{y:2.6, x:2, name: "Dog"},
{y:3.0, x:2, name: "Dog"},
{y:2.9, x:2, name: "Dog"},
{y:3.0, x:0.7, name: "Cat"},
{y:3.0, x:0.7, name: "Cat"},
{y:3.1, x:0.7, name: "Cat"},
{y:3.0, x:0.7, name: "Cat"},
{y:2.9, x:2.3, name: "Cat"},
{y:2.8, x:2.3, name: "Cat"},
{y:2.7, x:2.3, name: "Cat"},
{y:2.8, x:2.3, name: "Cat"},
{y:2.5, x:1, name: "Dog"},
{y:2.4, x:1, name: "Dog"},
{y:2.5, x:1, name: "Dog"},
{y:3.5, x:1, name: "Dog"},
{y:2.7, x:2, name: "Dog"},
{y:2.6, x:2, name: "Dog"},
{y:2.8, x:2, name: "Dog"},
{y:2.9, x:2, name: "Dog"}
]
var arr2 = [
{y:2.5, x:1, name: "Dog"},
{y:2.7, x:1, name: "Dog"},
{y:2.7, x:1, name: "Dog"},
{y:3.1, x:1, name: "Dog"},
{y:2.5, x:1, name: "Dog"},
{y:2.4, x:1, name: "Dog"},
{y:2.5, x:1, name: "Dog"},
{y:3.5, x:1, name: "Dog"}
]
我想這一點,但它不工作:
for (var i = 0; i < arr1.length; i++) {
if (arr1[i].x === 1 && arr1[i].name === "Dog"){
return ****;
arr2.push(***)
}
}
你想要做什麼['.filter()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter )是。 – Pointy
這應該很容易通過網絡搜索獲得一些方向 – charlietfl