Robert Brax
Robert Brax

Reputation: 7318

Generic Grouping of objects properties

I'm trying to group this object by name, so in fine I would be able to distinguish all names 'duval' from 'lulu':

const groupName = R.groupBy(R.prop('name'), [data]);

But this won't work on:

let data = {
    benj: {
        content : undefined,
        name    : 'duval',
        complete: false,
        height  : 181
    },

    joy: {
        content : undefined,
        name    : 'duval',
        complete: true
    },


    kaori: {
        content : undefined,
        name    : 'lulu',
        complete: true
    },

    satomi: {
        content : undefined,
        name    : 'lulu',
        complete: true
    }
}

Should I change the format of my object, or is there a way to do it in this kind of object ?

Upvotes: 1

Views: 247

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50797

Passing [data] to groupBy is not going to help much. You want to group a list containing a single item. The fact that that item has properties like 'bennj' and 'joy' rather than 'name' is only part of the issue.

You can get something that will work, I think, if this output would be useful:

{
  duval: {
    benj: {
      content: undefined,
      name: "duval",
      complete: false,
      height: 181
    },
    joy: {
      content: undefined,
      name: "duval",
      complete: true
    }
  },
  lulu: {
    kaori: {
      content: undefined,
      name: "lulu",
      complete: true
    },
    satomi: {
      content: undefined,
      name: "lulu",
      complete: true
    }
  }
}

But it's a bit more involved:

compose(map(fromPairs), groupBy(path([1, 'name'])), toPairs)(data)

toPairs converts the data to a list of elements something like this:

[
  "benj", 
  {
    complete: false, 
    content: undefined, 
    height: 181, 
    name: "duval"
  }
]

then groupBy(path[1, 'name']) does the grouping you're looking to do, by finding the name on the object at index 1 in this list.

And finally map(fromPairs) will turn these lists of lists back into objects.

It's not a particularly elegant solution, but it's fairly typical when you want to do list processing on something that's not really a list.

Upvotes: 2

Related Questions