Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check all value of Object except one

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.

like image 580
nb_nb_nb Avatar asked Oct 28 '25 12:10

nb_nb_nb


1 Answers

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);
like image 199
Taki Avatar answered Oct 31 '25 03:10

Taki