我有一系列对象

var data = [
    {
      "body_focus": "upper",
      "difficulty": "three",
      "calories_min": "122",
      "calories_max": "250"
    },
    {
      "body_focus": "upper",
      "difficulty": "three",
      "calories_min": "150",
      "calories_max": "280"
    },
    {
      "body_focus": "lower",
      "difficulty": "two",
      "calories_min": "100",
      "calories_max": "180"
    },
    {
      "body_focus": "total",
      "difficulty": "four",
      "calories_min": "250",
      "calories_max": "350"
    }
]


我想针对另一个对象过滤该对象数组

var myObj = {
    "upper": true,
    "three": true
}


所以现在myObj有一个键"upper""three",它们的值是true。因此,基于这些值,我想创建一个函数以获取data数组中的所有对象,其键"body_focus"的值为"upper",而"difficulty"键的值为"three"

因此该函数应仅返回这些对象

[
    {
      "body_focus": "upper",
      "difficulty": "three",
      "calories_min": "122",
      "calories_max": "250"
    },
    {
      "body_focus": "upper",
      "difficulty": "three",
      "calories_min": "150",
      "calories_max": "280"
    }
]


这就是我试图解决问题的方式

var entry;
var found = [];
for (var i = 0; i < data.length; i++) {
    entry = data[i];
    for(var key in myObj) {
        if(entry.body_focus.indexOf(key) !== -1) {
            found.push(entry);
            break;
        }
    }
}


我上面的代码仅检查键body_focus,那么如何同时检查body_focusdifficulty呢?可能看起来很傻,但是我被困了几个小时,找不到解决方案

最佳答案

我认为这应该可以解决问题。

var myObj = {
    "upper": true,
    "three": true
}
var found = [];
for (var i = 0; i < data.length; i++) {
    entry = data[i];
    if(myObj[entry.body_focus] && myObj[entry.difficulty]) {
      found.push(entry);
    }
}


使用myObj [entry.body_focus],您正在检查myObj是否具有upper属性,以及它是否为true。同样有困难。

关于javascript - 针对Javascript中的另一个对象过滤对象数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40933730/

10-13 01:50
查看更多