如何检查对象是否包含某个键?

时间:2019-02-25 16:49:15

标签: javascript object key

这是我的对象data

[{id:1, name:"Cat", category:{id:2, name:"Animals"}}]

我要检查它是否包含密钥category

这是我的方法:

if (data.hasOwnProperty("category")) {
console.log("data contains category");
}else {
  console.log("data does not contain category");
}

输出为:

  

数据不包含类别

应该相反...

4 个答案:

答案 0 :(得分:2)

您需要迭代数组。因此,您可以将代码放在notes = InputBox("You must input notes for " & Desc & " !", "Notes", notes)

forEach

如果您不想迭代,则需要传递索引,因为数据是对象数组。

let k = [{
  id: 1,
  name: "Cat",
  category: {
    id: 2,
    name: "Animals"
  }
}]

k.forEach(function(data) {
  if (data.hasOwnProperty("category")) {
    console.log("data contains category");
  } else {
    console.log("data does not contain category");
  }
})

答案 1 :(得分:1)

您还可以使用some检查数组中的任何对象是否符合特定条件:

void rotate_log (std::string logfile, uint32_t max_files, bool compress)
{
    sigset_t mask;

    sigemptyset (&mask);
    sigaddset (&mask, SIGTERM);
    sigaddset (&mask, SIGHUP);
    pthread_sigmask(SIG_BLOCK, &mask, NULL);

    // Do other stuff.
}

void Log::log (std::string message)
    {
        // Lock using mutex
        std::lock_guard<std::mutex> lck(mtx);

        _outputFile << message << std::endl;
        _outputFile.flush();
        _sequence_number++;
        _curr_file_size = _outputFile.tellp();

        if (_curr_file_size >= max_size) {
            // Code to close the file stream, rename the file, and reopen
            ...


            // Create an independent thread to compress the file since
            // it takes some time to compress huge files.
            if (!_log_compression_on)
            {
                std::thread(&Log::rotate_log, this, _logfile, _max_files, _compress).detach();
            }
        }
    }

答案 2 :(得分:1)

您需要遍历数组元素。您可以destructure assignment

let arr = [{id:1, name:"Cat", category:{id:2, name:"Animals"}}]

arr.forEach(({category})=>{
  if (category !== undefined) {
   console.log("data contains category");
  }else {
   console.log("data does not contain category");
  }
})

答案 3 :(得分:0)

那是一个只有一个索引的数组,因此您可以使用运算符in

"category" in data[0] // That checks if the property "category" exists.

如果索引不止一个,则应循环该数组。

运算符in还会检查继承的属性。

let data = [{id:1, name:"Cat", category:{id:2, name:"Animals"}}];
data.forEach((o, i) => console.log("Index:", i, " - Has category?:", "category" in o));