快速查看对象是否只具有值的特定属性的方法

时间:2016-12-10 23:31:27

标签: javascript object

在我的代码中,我有一个具有两个或六个属性的对象,我需要知道是否存在特定的值组合:

var myObject = {
  name: "John Smith",
  type = "person"
  prop1: "",
  prop2: "",
  prop3: "",
  prop4: ""
};

var myObject = {
  name: "My Business Name",
  type = "business"
};

我需要确定对象是否具有以下两个条件之一:

  1. name的值为" business"
  2. name有一个值,类型是" person"而其他四个属性没有价值。
  3. 如果它符合这两个条件中的一个,我把它放在一个地方,否则我把它放在另一个地方。如上所示,if type == "businessprop1-prop4不存在于对象中,但是if type == "person",它们确实存在。

    在不必每次都专门检查prop1 - prop 4的情况下,有什么简单的方法可以做到这一点?

    我正在查看lodash函数,看看是否有一个(或更多链接在一起)可以做到这一点,但我还没有确定一个。我也对纯JS选项持开放态度。

    感谢。

3 个答案:

答案 0 :(得分:0)

最简单的方法是以下方法(事实上,它使用的是vanilla JavaScript!):

var myObject1 = {
  name: "John Smith",
  type: "person",
  prop1: "",
  prop2: "",
  prop3: "",
  prop4: ""
};

var myObject2 = {
  name: "My Business Name",
  type: "business"
};

doStuff(myObject1);
doStuff(myObject2);

function doStuff(obj) {
  var properties = Object.keys(obj);

  switch (obj.type) {
    case "person":
      if (["name", "prop1", "prop2", "prop3", "prop4"].every(p => properties.includes(p))) {
        // Do stuff with a valid person 
        console.log("This person is fine!");
      }
      break;

    case "business":
      if (properties.includes("name")) {
        // Do stuff with a valid business
        console.log("This business is fine!");
      }
      break;
  }
}

答案 1 :(得分:0)

Checking for those conditions inside a function is one solution.   
var myObject = {
 name: "John Smith",
 type = "person"
 prop1: "",
 prop2: "",
 prop3: "",
 prop4: ""
};    
var validated = validateObject(myObject);
 function validateObject(obj){

   if((obj[name] &&  obj[type] === "business") || ((obj[name] &&  obj[type] === "person" && !obj[prop1] && !obj[prop2] && !obj[prop3] && !obj[prop4])) ){
    return true;
 }
 return false;
}

答案 2 :(得分:0)

您可以使用函数和单个if条件



var myObject = {
  name: "John Smith",
  type : "person",
  prop1: "",
  prop2: "",
  prop3: "",
  prop4: ""
};

var myObject1 = {
  name: "My Business Name",
  type: "business"
};

let checkProps = (obj, objName) => {
  let {name, type, prop1, prop2, prop3, prop4} = obj, len = name.length;
  if (len && type === "busines" || len && type === "person" 
      && prop1 + prop2 + prop3 + prop4 === "") {
    console.log(objName + " meets one of two conditions")
  } else {
    console.log(objName + " does not meet one of two conditions")
  }
}

checkProps(myObject, "myObject");

checkProps(myObject1, "myObject1");