I have a javascript object which contains error messages:
err: {
subject: '',
body: '',
recipient: ''
},
i want to disable a submit button based on whether an error is present. in the above declaration, there are no errors present.
i'm aware of Object.values(err)
but i do not know how to use the resulting list, which has a length of 3.
how would I do this? thank you
You can use Array.some()
on the Object.values()
to check if there are some error messages
let obj = { err: { subject: '', body: '', recipient: '' } }; let someErrors = Object.values(obj.err).some(e => e.length); console.log(someErrors);
const obj = {name: "Naimur", age: 21}
console.log("name" in obj) => true
console.log("age" in obj) => true
console.log("location" in obj) => false
Maybe like this:
var data={ err: { subject: '', body: '', recipient: '' }, }; if(data.err.subject!='' || data.err.body!='' || data.err.recipient!=''){ console.log('ERROR!'); }else{ console.log('ALL RIGHT!'); }
var err = {
subject: 'some error',
body: 'message',
recipient: 'Tom'
};
Object.values(err)
will return an array Array ["some error", 'message', 'Tom']
. Now, you can check the values of this array and then disable the button if these values satisfy some conditions.
Hope it helps.
I'm assuming that all of the elements have to equal '' for there to be a valid error. So you can use the .every()
method to check every element in the returned array. If only some of the elements have to equal '' for there to be an error message, just user .some()
instead.
let err = {
subject: '',
body: '',
recipient: ''
}
console.log(!Object.values(err).every(e => e === '')) //returns false meaning there isn't an error message
you may use .reduce() to return the sum of errors and also check if err has values with this code
if( (Object.values(err).length) ? Object.values(err).reduce((ac, next) => ac + next.length, 0) :false ){
console.log( 'there is errors' );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.