It is necessary to compare the array with the required fields with the object keys, if true, otherwise false.

const requiredFields = [ 'title', 'price', 'discount' ]; let form1 = { title: 'Товар Телепорт бытовой VZHIH-101', price: 7800, discount: 0 }; let form2 = { title: 'Товар Телепорт бытовой VZHIH-101', discount: 10 } if ( isValidPosition(form1, requiredFields) ) { console.log('Форма №1 заполнена верно'); } else { console.log('В форме №1 не заполнены необходимые поля'); } if ( isValidPosition(form2, requiredFields) ) { console.log('Форма №2 заполнена верно'); } else { console.log('В форме №2 не заполнены необходимые поля'); } function isValidPosition(form, settings) { let formKeys = Object.keys(form); console.log(formKeys); for (let i = 0; i < settings.length; i++) { if (settings.indexOf(formKeys[i]) === -1) { console.log('Форма заполнена не верно'); return false; } else { console.log('Форма заполнена верно'); return true; } } } 

  • one
    What is the question, actually? - n3r0bi0m4n
  • If there are 3 keys in the object as in the array, then true, if not, then false - Dmitry Moiseev
  • return true; remove from the loop, else can be removed. - greybutton

1 answer 1

It is possible to select through the filter all elements that are not in the object and if there are no such elements, then output true .

 // Функция проверки var isValid = function(obj, arr__properties) { var arr__gap = arr__properties.filter(property => obj[property] === undefined); return arr__gap.length === 0; }; // Данные var requiredFields = ['title', 'price', 'discount']; var form1 = { title: 'Товар Телепорт бытовой VZHIH-101', price: 7800, discount: 0 }; var form2 = { title: 'Товар Телепорт бытовой VZHIH-101', discount: 10 } // Проверка if (isValid(form1, requiredFields)) { console.log('Форма №1 заполнена верно'); } else { console.log('В форме №1 не заполнены необходимые поля'); } if (isValid(form2, requiredFields)) { console.log('Форма №2 заполнена верно'); } else { console.log('В форме №2 не заполнены необходимые поля'); } 

UPDATA:

At the prompt of the Grundy user, you can make a more brief check with the help of the every function.

 // Функция проверки var isValid = function(obj, arr__properties) { return arr__properties.every(property => obj[property] !== undefined); }; // Данные var requiredFields = ['title', 'price', 'discount']; var form1 = { title: 'Товар Телепорт бытовой VZHIH-101', price: 7800, discount: 0 }; var form2 = { title: 'Товар Телепорт бытовой VZHIH-101', discount: 10 } // Проверка if (isValid(form1, requiredFields)) { console.log('Форма №1 заполнена верно'); } else { console.log('В форме №1 не заполнены необходимые поля'); } if (isValid(form2, requiredFields)) { console.log('Форма №2 заполнена верно'); } else { console.log('В форме №2 не заполнены необходимые поля'); } 

  • if you use every local variable is not needed - Grundy
  • @Grundy, thank you. Added version with the function every - Yuri