简体   繁体   English

我如何切出包含值的所有数组对象并将它们存储在新数组中

[英]How can I slice out all of the array objects containing a value and storing them in a new array

So I have this array and I want to make a new array with those objects that have the swimming value in sports. 所以我有这个数组,我想用那些在运动中具有游泳价值的对象制作一个新的数组。

 var watchesArray = [
        {
          model: "Swim", 
          image:"",
          price: 149.99,
          sports:["Swimming", "Running"]
        },
        {
          model: "FR 10", 
          image:"",
          price: 129.99,
          sports:["Running"]

        },
        {
          model: "FR 15", 
          image:"",
          price: 199.99,
          sports:["Running"]

        },
    ];

So far I have this but I dont know how to add on to the sliced array with each go around in the for loop. 到目前为止,我已经有了这个,但是我不知道如何在for循环中每次添加到切片数组上。 How should I do this? 我应该怎么做?

 for (var i = 0; i < watchesArrayLength; i++) {
        if (watchesArray[i].sports.indexOf("Swimming") > -1) {
            var runningWatchArray = watchesArray.slice(i);

        }

    }

You can use .filter() method: 您可以使用.filter()方法:

watchesArray = [...];

var result = watchesArray.filter(function(watch) {
    return watch.sports.indexOf('Swimming') !== -1;
});

If I understand correctly, what you want is 如果我理解正确,您想要的是

var runningWatchArray = [];
for (var i = 0; i < watchesArrayLength; i++) {
    if (watchesArray[i].sports.indexOf("Swimming") > -1) {
        var watch = watchesArray.slice(i);
        runningWatchArray.push(watch);
    }
}

You could also use forEach to loop through each item of the watchesArray... 您还可以使用forEach遍历watchersArray的每个项目...

var runningWatchArray = new Array();

watchesArray.forEach(function(watch){
      if (watch.sports.indexOf("Swimming") > -1) {
        runningWatchArray.push(watch);
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM