【问题标题】:How to check if key exists in array of object如何检查对象数组中是否存在键
【发布时间】:2018-01-20 13:56:50
【问题描述】:

我试图找出给定的键是否存在于对象数组中。如果 value 键存在,那么我想返回 true,否则返回 false。

我从文本框中输入键,然后检查该键是否存在于对象数组中,但我无法得到它。

这是我尝试过的

代码:

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

var val = $("input[name='type_ahead_input']").val();

if (obj[val]) {
    console.log('exists');
} else {
    console.log('does not exist');
}

如果我将输入作为对象数组中存在的“the carribean”提供,即使它在控制台中的输出也不存在。

我该如何解决这个问题?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

您可以过滤对象数组并仅返回具有所需键的对象。然后,如果结果数组的长度大于零,则表示存在具有该键的元素。

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "the carribean";

var exists = obj.filter(function (o) {
  return o.hasOwnProperty(val);
}).length > 0;

if (exists) {
    console.log('exists');
} else {
    console.log('does not exist');
}

如果数组包含具有所需键的对象,无论其值为undefined 还是null,这将返回true

【讨论】:

    【解决方案2】:

    您可以使用typeof 来检查key 是否存在

    if (typeof obj[0][val] !== "undefined" ) {
        console.log('exists');
    } else {
        console.log('does not exist');
    }
    

    注意:有索引 0 因为您正在检查的对象是数组 obj 的元素 0


    这是一个小提琴:

    var obj = [{
    		"7364234":"hsjd",
    		"tom and jerry":"dsjdas",
    		"mickey mouse":"kfjskdsad",
    		"popeye the sailor man":"alkdsajd",
    		"the carribean":"kasjdsjad"
    	}];
    
    	if ( typeof obj[0]["the carribean"] !== 'undefined' ) {
    		console.log('exists');
    	} else {
    		console.log('does not exist');
    	}

    正如下面 Cristy 所建议的,您也可以使用obj[0][val] === undefined

    您还可以:

    var obj = [{
        "7364234":"hsjd",
        "tom and jerry":"dsjdas",
        "mickey mouse":"kfjskdsad",
        "popeye the sailor man":"alkdsajd",
        "the carribean":"kasjdsjad"
    }];
    
    var val = "7364234";
    
    if ( val in obj[0] ) {
        console.log('exists');
    } else {
        console.log('does not exist');
    }
    

    【讨论】:

    • obj[0][val] === undefined 更容易读/写/理解。另请注意,即使值未定义,键也可以存在。应使用 in 运算符:val in obj[0]
    【解决方案3】:

    您的 obj 是一个数组,因此要检测 数组 中的任何对象中是否存在键,您需要迭代数组,然后查看每个对象的键。

    var objArr = [{
      "7364234": "hsjd",
      "tom and jerry": "dsjdas",
      "mickey mouse": "kfjskdsad",
      "popeye the sailor man": "alkdsajd",
      "the carribean": "kasjdsjad"
    }]
    
    const contains = (string) =>
      objArr.findIndex(
        // Is the string contained in the object keys?
        obj => Object.keys(obj).includes(string)
      ) !== -1
    
    console.log(contains('the carribean'))
    console.log(contains('spaghetti'))

    【讨论】:

      【解决方案4】:

      我建议使用Array.some() 来了解某个键是否存在,并使用Array.find() 来获取找到的键的值,以及一些最近的语法:

      let arr = [{"foo": 1}, {"bar":2}];
      
      function isKeyInArray(array, key) { 
        return array.some(obj => obj.hasOwnProperty(key)); 
      }
      
      function getValueFromKeyInArray(array, key) { 
        return array.find(obj => obj[key])?.[key]; 
      }
      
      console.log(isKeyInArray(arr, "foo"), isKeyInArray(arr, "bar"), isKeyInArray(arr, "baz"));
      console.log(getValueFromKeyInArray(arr, "foo"), getValueFromKeyInArray(arr, "bar"), getValueFromKeyInArray(arr, "baz"));
      

      【讨论】:

        【解决方案5】:

        这是因为您有一个对象数组 [{...},{...}] 而不仅仅是一个对象 {...}。 要么使用一个对象并保留你的测试,要么使用 Array.find 方法来搜索具有valproperty 的对象是否存在于你的数组中。例如:

        var objArr = [{
            "7364234":"hsjd",
            "tom and jerry":"dsjdas",
            "mickey mouse":"kfjskdsad",
            "popeye the sailor man":"alkdsajd",
            "the carribean":"kasjdsjad"
        }]
        
        let val = $("input[name='type_ahead_input']").val();
        
        var existingObj = objArr.find(function(element) {
          return typeof element[val] !== 'undefined';
        });
        
        if (existingObj[val]) {
        console.log('was found');
        } else {
        console.log('not-found');
        

        见:https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/find

        【讨论】:

          【解决方案6】:

          需要从数组obj[0][val]中获取对象

          var validate = function() {
            var obj = [{
              "7364234": "hsjd",
              "tom and jerry": "dsjdas",
              "mickey mouse": "kfjskdsad",
              "popeye the sailor man": "alkdsajd",
              "the carribean": "kasjdsjad"
            }];
          
            var val = $("input[name='type_ahead_input']").val();
            console.log(val);
            if (obj[0][val]) {
              console.log('exists');
            } else {
              console.log('does not exist');
            }
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          
          <input name="type_ahead_input" value="" onkeyup="validate()">

          【讨论】:

            【解决方案7】:

            @E。 Sundin的答案是我认为最简单的。就我而言,我做了如下...

            let o = { 
                id: 2, 
                name: "jack", 
                age: 54, temp: 2323
            }
            
            if(!Object.keys(o).includes('id')) throw new BadRequest("Id was missing!");
            

            如果你有一个通过循环完成的对象数组。

            if(!o.every(elm => Object.keys(o).includes('id')) throw new BadRequest("Id was missing!");
            

            希望它会起作用。

            【讨论】:

              猜你喜欢
              • 2020-07-11
              • 1970-01-01
              • 1970-01-01
              • 2020-05-02
              • 1970-01-01
              • 2013-09-26
              • 1970-01-01
              • 1970-01-01
              • 2012-02-04
              相关资源
              最近更新 更多