在嵌套数组中按值查找和删除数组中的对象

时间:2015-06-20 02:00:23

标签: javascript arrays json

我有一个具有以下结构的数组:

var questions = [
    {"answer":
        ["A1", "A2", "A3"]
    },
    {"answer":
        ["B1"]
    },
    {"answer":
        ["C1", "C2"]
    }
]

我还有一系列对象,如下所示:

var answers = [
    {"value": "A1"},
    {"value": "A512"},
    {"value": ""},
    {}
];

对于answers中的每个对象(如果它不是{}),我想查找相应的值是否出现在questions中的某个对象中。如果是,我想更新counter变量并从questions中删除该对象。我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

试试这个

var questions = [{
    "answer": ["A1", "A2", "A3"]
}, {
    "answer": ["B1"]
}, {
    "answer": ["C1", "C2"]
}];
var count = 0;
answers.forEach(function(ans) {
    var flag = isExists(ans.value);
    flag && count++;
});
console.log(count);

function isExists(value) {

   return questions.some(function(ques) {
        var ind = ques.answer.indexOf(value);
        if (ind > -1) {
            ques.answer.splice(ind, 1);
            return true;
        }
    });

}