Skip to content Skip to sidebar Skip to footer

Count Length Properties Of Each Object.entry

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

Solution 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)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Solution 2:

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"}
];
  
constfilterObj = (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));

Post a Comment for "Count Length Properties Of Each Object.entry"