Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function proposal - flatMapValues() #6

Closed
glenveegee opened this issue May 19, 2020 · 2 comments
Closed

Function proposal - flatMapValues() #6

glenveegee opened this issue May 19, 2020 · 2 comments

Comments

@glenveegee
Copy link

For objects, it's currently very difficult (if not impossible) to have access to the key and the value in the same scope of the expression. This function would decompose objects into Array<[key:value]> such that every key corresponds to a decomposed value.

In javascript (typescript) this might look something like:

registerFunction(
  'flatMapValues',
  ([inputObject]) => {
    return Object.entries(inputObject).reduce((flattened, entry) => {
      const [key, value]: [string, any] = entry;
      if (Array.isArray(value)) {
        return [...flattened, ...value.map(v => [key, v])];
      }
      return [...flattened, [key, value]];
    }, [] as any[]);
  },
  [{ types: [TYPE_OBJECT, TYPE_ARRAY] }],
);

Which produces the following:

jmespath.search( { a: [1, 3, 5], b: [2, 4, 6] }, "flatMapValues(@)")
// OUTPUTS: [
//      ['a', 1],
//      ['a', 3],
//      ['a', 5],
//      ['b', 2],
//      ['b', 4],
//      ['b', 6],
//    ]

jmespath.search({ a: [true, { x: 3 }, null, 1234, ['XXX']], b: { x: 2 } }, "flatMapValues(@)")
// OUTPUTS: [
//      ['a', true],
//      ['a', { x: 3 }],
//      ['a', null],
//      ['a', 1234],
//      ['a', ['XXX']],
//      ['b', { x: 2 }],
//    ]

jmespath.search([ [1, 3, 5], [2, 4, 6] ], "flatMapValues(@)")
// OUTPUTS: [
//      ['0', 1],
//      ['0', 3],
//      ['0', 5],
//      ['1', 2],
//      ['1', 4],
//      ['1', 6],
//    ]

These could then be piped to expressions that filter on keys or project keys into new objects/arrays

@innovate-invent
Copy link

Could this be done with the proposed let() function? I like this proposal but it could potentially violate the "one way of doing things" policy that has kept JMESPath simple.

@glenveegee
Copy link
Author

This and an entire class of other proposed functions would definitely be supported by the let function. JEP 11: The let() Function is a great proposal as it generalises this core issue proposed here. Given it was proposed in 2015 I really hope there will be some progress on it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants