-4

I have an object, for example ,

let obj = {
  name: '',
  age: 16, 
  address: '', 
  city: '', 
  pin: 4564
}

I want the length of element which have a value rather than 0 or undefined or ''. my obj has 2 elements which have value( age and pin) soI want the length of obj as 2

pilchard
  • 12,414
  • 5
  • 11
  • 23
Lex V
  • 1,414
  • 4
  • 17
  • 35
  • 3
    What have you tried so far to solve this on your own? -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) + [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Andreas Oct 27 '22 at 09:33
  • also [Count the number of trues in a JavaScript object](https://stackoverflow.com/questions/52846805/count-the-number-of-trues-in-a-javascript-object) – pilchard Oct 27 '22 at 09:50

1 Answers1

5

using Object.values and filter with Boolean on each element on it maybe

let obj = {
  name: '',
  age: 16, 
  address: '', 
  city: '', 
  pin: 4564
}

console.log(Object.values(obj).filter(Boolean).length)
KcH
  • 3,302
  • 3
  • 21
  • 46
  • 1
    actually the `reduce` in the above [linked duplicate](https://stackoverflow.com/questions/52846805/count-the-number-of-trues-in-a-javascript-object) is arguably a better 'one-liner' as it avoids creating an intermediary array. – pilchard Oct 27 '22 at 10:03
  • @pilchard totally makes sense, great one good to learn – KcH Oct 27 '22 at 10:06