我想根据键数组获得对象中不存在或不存在的键的列表。
我现在能做的是验证它是否存在,但我想知道哪个密钥存在或不存在。
const obj = {Password: '123456', Username: 'MeMyselfAndI'}
const checkFields= ['Method', 'Password', 'Username','email']
const result = checkFields.every(key => obj.hasOwnProperty(key));
console.log(result); // false
我希望这段代码能帮助你
checkFields.filter(o=>!(Object.keys(obj)).includes(o))
您可以创建一个分区,将键分隔在一个对象中:
const obj = {Password: '123456', Username: 'MeMyselfAndI'}
const checkFields = ['Method', 'Password', 'Username', 'email']
const createFieldPartition = (ob, fields) => {
const keys = Object.keys(ob);
return fields.reduce( (acc, cur) => {
if (keys.includes(cur) ) { acc.existing.push(cur); }
else { acc.notExisting.push(cur); }
return acc
}, {existing:[], notExisting:[]} );
}
console.log(createFieldPartition(obj, checkFields))
const obj = {Password: '123456', Username: 'MeMyselfAndI'}
const checkFields= ['Method', 'Password', 'Username','email'];
let existing_fields = [];
let unexisting_fields = [];
checkFields.map(field => {
if(Object.keys(obj).indexOf(field) != -1) {
existing_fields.push(field);
} else {
unexisting_fields.push(field);
}
});
console.log("Unexisting fields", unexisting_fields);
console.log("Eexisting fields", existing_fields);
您可以使用in
运算符来检查对象是否包含键。
如果指定的属性在指定的对象或其原型链中,in运算符将返回true。
const obj = {Password: '123456', Username: 'MeMyselfAndI'}
const checkFields= ['Method', 'Password', 'Username','email']
const result = checkFields.filter(key => key in obj);
console.log(result);
在数组上循环并创建一个对象,其中属性设置为true
或false
。
const obj = {Password: '123456', Username: 'MeMyselfAndI'};
const checkFields= ['Method', 'Password', 'Username','email'];
const result = { 'true': [], 'false': [] };
for (let el of checkFields) {
const value = obj[el] ? true : false;
result[value].push(el);
}
console.log(`Exists: ${result.true.join(' ')}`);
console.log(`Do not exist: ${result.false.join(' ')}`);