1

So I want to be able to count the number of properties within each object in an array...

    value = [
   0: { personId: "0003678", seniorStatus: "Yes", juniors: "maybe" }, //3
   1: { personId: "0001657", seniorStatus: "No", juniors: "No" }, //3
   2: { personId: "0002345", seniorStatus: "No", juniors: "No", infants: "Maybe" } //4

Basically I want to do this to check for a change. If more than 3 properties in any of the objects. I know how to count the number of objects, in this case there are 3. But need to count the properties within. If more than 3 return true.

I am struggling to find anything that gets past the counting of Objects question. I am using lodash if useful for an answer.

Tom Rudge
  • 3,188
  • 8
  • 52
  • 94

2 Answers2

1

Map the array to the length of the Object.keys() of each object and check if greater than 3:

const values = [{"personId":"0003678","seniorStatus":"Yes","juniors":"maybe"},{"personId":"0001657","seniorStatus":"No","juniors":"No"},{"personId":"0002345","seniorStatus":"No","juniors":"No","infants":"Maybe"}]
   
const result = values.map(o => Object.keys(o).length > 3)

console.log(result)

Or use lodash's _.size() to get the number of properties in each object, and then check if 3 is less than the number with _.lt():

const values = [{"personId":"0003678","seniorStatus":"Yes","juniors":"maybe"},{"personId":"0001657","seniorStatus":"No","juniors":"No"},{"personId":"0002345","seniorStatus":"No","juniors":"No","infants":"Maybe"}]
   
const result = values.map(_.flow(
  _.size,
  _.partial(_.lt, 3)
))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • May also add `values.map(o => Object.keys(o).length > 3)` to complete a question –  Feb 10 '19 at 19:41
0

Consider this as an extension of Ori Drori approach. In the case you need to get the objects that have more than N keys you can use filter() like this:

const input = [
  {personId:"0003678", seniorStatus:"Yes", juniors:"maybe" },
  {personId:"0001657", seniorStatus:"No", juniors:"No" },
  {personId:"0002345", seniorStatus:"No", juniors:"No", infants:"Maybe"}
];
  
const filterObj = (objs, numProps) =>
{
    return objs.filter(o => Object.keys(o).length > numProps);
}
  
console.log("Objs with more than 3 props: ", filterObj(input, 3));
console.log("Objs with more than 2 props: ", filterObj(input, 2));
Shidersz
  • 16,846
  • 2
  • 23
  • 48