gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:39:41 27 4
gpt4 key购买 nike

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

我正在使用 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 过滤数组,返回满足过滤功能的项目列表,同时保持原始数组不变。 (参见 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>

关于javascript - 如何从 json 对象中获取匹配元素的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41009545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com