简体   繁体   English

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

[英]How to get index of matched element from json object?

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"
}];

I am using grep to match object. 我正在使用grep来匹配对象。

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);

jQuery.grep filters an array, returning a list of the items that satisfied the filter function while leaving the original array untouched. jQuery.grep过滤一个数组,返回满足过滤功能的项目列表,同时保持原始数组不变。 (See the jQuery docs .) (请参阅jQuery文档 。)

I'm not sure why you wanted to access the index; 我不确定您为什么要访问索引; I assume you wanted access to the original object that satisfied the filter. 我假设您想访问满足过滤条件的原始对象。 This could be accomplished by returning true from your filter function, and then looping through the matches array afterwards. 这可以通过从过滤器函数返回true ,然后循环遍历matchs数组来实现。

 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> 

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

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