简体   繁体   中英

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.

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. (See the jQuery docs .)

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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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