如何检查对象是否需要键

时间:2018-09-19 18:47:36

标签: javascript angularjs node.js reactjs

最佳方法是什么? 如果有更好的方法,我也会对lodash方法感兴趣

var myObj = {
  name: 'John',
  age: 20,
  sex: male
}

我想看看myObj是否具有“名称”和“年龄”键

我的方法-很好

var myObj = {
  name: 'John',
  age: 20,
  sex: 'male'
}
var value;

function result() {
  if (myObj.hasOwnProperty('name') && myObj.hasOwnProperty('age')) {
    value = true;
  } else {
    value = false;
  }
}
result();
console.log(value);

我还可以使用(myObj中的“键”)

但是实际上我有一个安静的大对象,需要检查它们是否具有特定的键。 寻找更好的方法

7 个答案:

答案 0 :(得分:2)

将所需的键放入数组中

let requiredKeys = ["name", "age"];

然后使用Array.every方法和Object.keys

let objectKeys = Object.keys(myObj);
let hasRequiredKeys = requiredKeys.every(k => objectKeys.includes(k));

答案 1 :(得分:1)

使用 lodash has 方法

var _ = require('lodash');
var myObj = {
   name: 'John',
   age: 20,
   sex: male
}

var has_keys = _.has(myObj, ['name', 'age', 'sex']);
// has_keys => true

答案 2 :(得分:0)

function validateObj (myObj) {
   var nameFound = false;
   var ageFound = false;
   for (x in myObj) {
       if (x === "name") nameFound = true;
       if (x === "age")  ageFound = true;
       if (ageFound && nameFound) return true;
   }
   return (ageFound && nameFound)
}

答案 3 :(得分:0)

创建一个键数组。使用Array.every()迭代数组,并使用Object.hasOwnProperty()检查每个键是否在对象中:

const myObj = {
  name: 'John',
  age: 20,
  sex: 'male'
};

const hasKeys = (obj, keys) => keys.every(key => obj.hasOwnProperty(key));
  
console.log(hasKeys(myObj, ['name', 'age']));

console.log(hasKeys(myObj, ['name', 'title']));

答案 4 :(得分:0)

您可以只使用in运算符进行恒定时间查找(无需将键转储到线性查找的数组中):

var myObj = {
  name: "John",
  age: 20,
  sex: "male"
};

console.log(["name", "age"].every(e => e in myObj));

答案 5 :(得分:0)

这个问题有一些微妙之处可能重要,也可能不重要。

Javascript中的对象具有可以从其他对象继承属性的原型。尚不清楚如果在原型上找到了所需的属性之一,myObj是否有效。

这是一个例子:

const parent = {
    name: 'John',
    age: 20,
    sex: 'male'
  }
 
const requiredKeys = ['name', 'age']

let valid = requiredKeys.every(key => parent.hasOwnProperty(key))

// valid becuase parent has name and age
console.log("Parent valid:", valid)

// but what about child that inherits from parent:

let child = Object.create(parent)

valid = requiredKeys.every(key => child.hasOwnProperty(key))

// not valid becuase child doesn't directly has name and age
console.log("Child Valid:", valid)

// yet those properties seem to exist because you can get them through parent's prototype:
console.log("Child name and age:", child.name, child.age)

// you can test up the protoytpe chain with …in:

valid = requiredKeys.every(key => key in child)

// now valid becuase child has name and age somewhere in the prototype chain 
console.log("Child Valid (with prototype):", valid)

所以问题将是:哪一种最适合您的用例。

答案 6 :(得分:0)

我喜欢对深层物体使用lodash get。原因是在未定义任何深层属性或不存在任何深层属性时处理问题。代替控制台和其他东西上的错误-

var object = {'a':[{'b':{'c':3}}]};

_。get(object,'a [0] .b.c'); // => 3

_。get(object,['a','0','b','c']); // => 3

_。get(object,'a.b.c','default'); // =>'默认'

来自-https://lodash.com/docs/4.17.10#get