通过json_encode
从PHP数组转换JSON数组。我想通过JavaScript / JQuery从该JSON数组中找到特定元素的索引。
首先,用户将选择一个选项,其中的值将是人员的ID。
<select class="form-control" id="pname" name="pname" required>
<option value="">--Please select--</option>
<option value="312">John Doe</option>
<option value="313">Mark Angel</option>
<option value="314">Chloe Karl</option>
</select>
然后通过JavaScript / JQuery,我需要从下面给出的JSON数组中获取所选选项的值的索引。
{
"p_id":{"1":312,"2":313,"3":314},
"p_name":{"1":"John Doe","2":"Mark Angel","3":"Chloe Karl"},
"p_dob":{"1":"1983","2":"1993","3":"1987"},
"p_sex":{"1":"Male","2":"Male","3":"Male"}
}
答案 0 :(得分:0)
您有一个不是数组的javascript对象文字,可以使用for in
循环进行迭代并找到所需的内容。
var obj = {
p_id: { "1": 312, "2": 313, "3": 314 },
p_name: { "1": "John Doe", "2": "Mark Angel", "3": "Chloe Karl" },
p_dob: { "1": "1983", "2": "1993", "3": "1987" },
p_sex: { "1": "Male", "2": "Male", "3": "Male" }
};
var selected = 313;
for (p in obj.p_id) {
if (obj.p_id[p] == selected) {
console.log(p);
}
}
如果您有来自php的原始响应,则将有一个JSON。您可以使用JSON.parse()
答案 1 :(得分:0)
如果我没有误解/曲解您的问题,那么您需要使用此代码段。
要做的步骤:
首先在onchange
元素上添加select
事件。
使用JSON.parse()
使用Array.prototype.filter()
获取所选用户的密钥/索引。
function getSelect() {
var obj = JSON.parse('{"p_id":{"1":312,"2":313,"3":314},"p_name":{"1":"John Doe","2":"Mark Angel","3":"Chloe Karl"},"p_dob":{"1":"1983","2":"1993","3":"1987"},"p_sex":{"1":"Male","2":"Male","3":"Male"}}');
var ids = obj.p_id;
var e = document.getElementById("pname");
var user = e.options[e.selectedIndex].value;
//console.log(ids, user, Object.keys(ids))
if(user && user!=""){
var k = Object.keys(ids).filter((key) => {
return ids[key] == user;
})[0];
console.log(k)
}else {
console.log('Select an option first');
}
}
<select class="form-control" onchange="getSelect()" id="pname" name="pname" required>
<option value="">--Please select--</option>
<option value="312">John Doe</option>
<option value="313">Mark Angel</option>
<option value="314">Chloe Karl</option>
</select>