Jalal Qureshi
Jalal Qureshi

Reputation: 35

Determine if a JavaScript object contains all keys from array & none of the keys have empty value

Given a javascript object & an array containing keys which the object must contain

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

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

Need help writing a single if statement:

For ALL keys in the person_keys array that are NOT in the JavaScript object (person)

&&

For all values of the keys which have a value that is an empty string

throw an error indicating all the keys which are not in the JavaScript object (person) and all the key values in the JavaScript object which have an empty string as their value.

Ex: person_keys array below contains 4 values (id, name, age, weight, height)

person object below does not contain the key weight & height, and the key age has an empty string as its value

The output should be: "The keys weight and height do not exist and the key age has an empty value"

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

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

Upvotes: 0

Views: 506

Answers (1)

Darshit Dhameliya
Darshit Dhameliya

Reputation: 146

You can improve error msg by checking notAvailable and emptyVals array value.

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)

Upvotes: 1

Related Questions