如何从json对象获取匹配元素的索引?

时间:2016-12-07 04:40:19

标签: javascript jquery json

var InputName = 'checkbox-group-1479370460494';
var InputType = 'checkbox-group';

var returnedIndex = $.grep(formRenderData, function(element, index){
    if(( (element.name == InputName) || (element.label == InputName)|| (element.name == InputName.substr(0,InputName.length - 2)) ) && element.type == InputType){
        return index;
    }
});

console.log(returnedIndex);

我使用grep匹配对象。

Flexible_Gazetteer

1 个答案:

答案 0 :(得分:2)

jQuery.grep过滤一个数组,返回满足过滤功能的项目列表,同时保持原始数组不变。 (见the jQuery docs。)

我不确定你为什么要访问索引;我假设你想访问满足过滤器的原始对象。这可以通过从过滤器函数返回true,然后循环遍历matches数组来完成。



var InputName = 'checkbox-group-1479370460494';
var InputType = 'checkbox-group';
var formRenderData = [{"type": "checkbox-group","label": "Checkbox Group","className": "checkbox-group","name": "checkbox-group-1479370460494","values": [{"label": "Option 1","value": "option-1","selected": true},{"label": "Option 2","value": "option-2"},{"label": "Option 3","value": "option-3"}]},{"type": "paragraph","subtype": "p","label": "Paragraph","className": "paragraph"}]

var matches = $.grep(formRenderData, function(element, index){
    if(( (element.name == InputName) || (element.label == InputName)|| (element.name == InputName.substr(0,InputName.length - 2)) ) && element.type == InputType){
        return true
    }
});

console.log(matches); // [Array]

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;