0

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: "",
}
4
  • 2
    what does not work? Commented May 13, 2021 at 6:57
  • Well the in keyword checks if an object has a given key, and for empty strings you can just check ` === ''` so what specifically is the problem? Commented May 13, 2021 at 6:58
  • 2
    Homework questions are fine, but you need to at least have an attempt yourself. Commented May 13, 2021 at 7:03
  • Not a homework question. Building an application to learn JavaScript and I want to throw errors that are specific. Commented May 13, 2021 at 7:20

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.