确定一个 JavaScript 对象是否包含数组中的所有键,并且所有键都没有空值

问题描述

给定一个 javascript 对象和一个包含对象必须包含的键的数组

const person_keys = ['id','name','age'];

let person = {
  name: "person",id: "blue",age: "",}

需要帮助编写一个 if 语句:

对于 person_keys 数组中所有不在 JavaScript 对象 (person) 中的键

&&

对于所有值为空字符串的键值

抛出一个错误,指出所有不在 JavaScript 对象(person)中的键和 JavaScript 对象中所有以空字符串作为值的键值。

例如: 下面的 person_keys 数组包含 4 个值(id、name、age、weight、height)

下面的person对象不包含key weight&height,keyage值为空字符串

输出应该是: “key weight 和 height 不存在,key age 为空值”

const person_keys = ['id','age','weight','height'];

let person = {
  name: "person",}

解决方法

您可以通过检查 notAvailable 和 emptyVals 数组值来改善错误消息。

const person_keys = ['id','name','age','weight','height'];

let person = {
  name: "person",id: "blue",age: "",}

const notAvailable = [];
const emptyVals = [];
person_keys.forEach(key => {
  if(!person.hasOwnProperty(key)){
    notAvailable.push(key);
  }
  else{
    if(person[key] == null || person[key] == ""){
      emptyVals.push(key);
    }
  }
});
const errorMsg = `The key ${notAvailable.join(' and ')} do not available and the key ${emptyVals.join(' and ')} has empty values`;
console.log(errorMsg)