【问题标题】:How to verify a key of object exists within a Javascript array of objects?如何验证 Javascript 对象数组中是否存在对象键?
【发布时间】:2022-11-21 17:01:20
【问题描述】:

我有一个如下所示的数组。

cont arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

我能知道如何验证数组对象中是否存在“用户名”吗?

【问题讨论】:

    标签: javascript arrays arrayobject


    【解决方案1】:

    hasOwnProperty 可用于此

    let  x = {
        y: 1
    };
    console.log(x.hasOwnProperty("y")); //true
    console.log(x.hasOwnProperty("z")); //false
    

    更多信息请参考SO related question

    【讨论】:

    • 你能包括如何将它与 OP 一起使用吗大批arr.hasOwnProperty("username") == false jsfiddle.net/j13kapcn
    【解决方案2】:

    如果你想知道数组中是否存在特定的用户名值,你可以使用Array.some()来完成

    const arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
    
    const checkName = (arr,name) => arr.some(a => a.username === name)
    
    console.log(checkName(arr,'bill'))
    console.log(checkName(arr,'billA'))

    如果只想检查数组中是否存在用户名属性,可以结合Object.keys()Array.flat()Array.includes()来实现

    const arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
    
    const checkName = (arr,name) => arr.map(a =>Object.keys(a)).flat().includes(name)
    
    
    console.log(checkName(arr,'username'))
    console.log(checkName(arr,'username1'))

    【讨论】:

    • OP 想要验证对象中是否存在密钥。
    【解决方案3】:

    const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ];
    
    // get array of usernames from array of objects
    const usernames = arr.map(obj => obj.username);
    console.log(usernames);
    console.log(usernames.includes('bill'));
    console.log(usernames.includes('paul'));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多