我在嵌套对象中有一个对象。我想检测对象名称是否存在,获取该对象的文本值
我尝试通过元素内部的for循环到达。但是我只能迈出一步。
var data = [
{ "option1": "selectedoption1" },
{ "option2": "selectedoption2" },
{ "option2": "selectedoption3" },
{ "option2": "selectedoption4" }
]
var selectedOption = jQuery(".option .value").eq(0).text();
for(var i = 0; i < data.length; i++) {
if(data[i].selectedOption) {
console.log(selectedOption);
// i want to reach selectedoption1
}
}
最佳答案
由于它们都只有一个键/值,因此可以使用find()
并将其与Object.values
中的第一个值进行比较
var data = [
{ "option1": "selectedoption1" },
{ "option2": "selectedoption2" },
{ "option2": "selectedoption3" },
{ "option2": "selectedoption4" }
]
let looking_for = "selectedoption2"
let found = data.find(obj => Object.values(obj)[0] == looking_for)
console.log(found)
// undefined if value doens't exist:
let not_here = "some_other_value"
found = data.find(obj => Object.values(obj)[0] == not_here)
console.log(found)