Reputation: 1381
I have a JavaScript.The object looks something like
{date: "2019-10-03", hello: 0, yo: 0, test: 0}
Can I check to see if all values in object are ==0
except for the date?
I am not sure how I can go about coding that.
Upvotes: 4
Views: 8807
Reputation: 33
Here is I think simplest answer, you can simply separate Object Keys & Values and than check "not date" and "equals to 0" in for loop.
let main_obj = {date: "2019-10-03", hello: 0, yo: 0, test: 0};
let obj_keys = Object.keys(main_obj);
let obj_values = Object.values(main_obj);
for(i = 1; i <= obj_keys.length; i++) {
if(obj_keys[i] != 'date' && obj_values[i] == 0) {
console.log('Found Zero Number ' + i);
}
}
Upvotes: 0
Reputation: 17190
Here is another alternative that uses Object.entries() in combination with Array.every():
const allZeroExceptDate = o =>
Object.entries(o).every(([k, v]) => k === "date" || v === 0);
console.log(allZeroExceptDate(
{date: "2019-10-03", hello: 0, yo: 0, test: 0}
));
console.log(allZeroExceptDate(
{hello: 0, yo: 0, test: 0}
));
console.log(allZeroExceptDate(
{date: "some-date", hello: 0, yo: 0, test: 33}
));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Upvotes: 1
Reputation: 17654
Use destructuring to extract the date and the rest of the properties and calculate the sum
of the Object.values using Array.reduce :
const obj = { date: "2019-10-03", hello: 0, yo: 0, test: 0 };
const { date, ...rest } = obj;
const sum = Object.values(rest).reduce((sum, curr) => sum + curr, 0);
const allZeros = sum === 0 ? true : false;
console.log(allZeros);
( keep in mind that this will create a variable date
in the current scope )
or, use Array.every
const obj = { date: "2019-10-03", hello: 0, yo: 0, test: 0 };
const { date, ...rest } = obj;
const allZeros = Object.values(rest).every(e => e === 0);
console.log(allZeros);
Upvotes: 12
Reputation: 1257
I think you're looking for a for...in loop with an if statement:
var obj = {date: "2019-10-03", hello: 0, yo: 0, test: 0};
for (var prop in obj) {
if ((prop !== 'date') && (obj[prop] === 0)) {
console.log("check for zero passed and NOT date");
}
}
Upvotes: 0
Reputation: 437
let testObj = {date: "2019-10-03", hello: 0, yo: 0, test: 0};
let result = true;
for(const key of Object.keys(testObj)) {
if(key !== 'date' && testObj[key] !== 0) result = false;
}
return result;
We can loop through the keys of an object using Object.keys(someObj)
and check if the key is equal to date. We can also perform the value checks in the same loop.
Upvotes: 0
Reputation: 359
You can do a loop over properties:
let obj = {date: "2019-10-03", hello: 0, yo: 0, test: 0}
let isAllZero = true
for (const key in obj) {
if (obj.hasOwnProperty(key) && key !== 'date' && obj[key] !== 0) {
isAllZero = false
}
}
Upvotes: 0