如何按文本比较嵌套对象

时间:2019-05-17 21:47:27

标签: javascript jquery object

我在嵌套对象中有一个对象。我想检测对象名称是否存在,获取该对象的文本值 我尝试通过元素内部的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
      }
    }

1 个答案:

答案 0 :(得分:1)

由于它们都只有一个键/值,因此您可以使用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)