Skip to content

Arrays with Objects #17

@PaulKruger

Description

@PaulKruger

I didn't notice whether you had or planned to develop functions that included arrays that contained objects.

So for example if wanted to return true if there is an apple pie in group of pies:
var rules = { "and" : [
{"<" : [ { "var" : "temp" }, 110 ]},
{"==" : [ { "var" : "pies.filling" }, "apple" ] }
] };

var data = { "temp" : 100, "pies" : [{ "filling" : "apple" }, { "filling" : "cherry" }]};

jsonLogic.apply(rules, data);
// true

Activity

jwadhams

jwadhams commented on Nov 10, 2016

@jwadhams
Owner

You could build a custom operaton using dotty's search method and then using that with in, like

jsonLogic.add_operation('var_search', function(key){
  return dotty.search(this, key); //In custom operations "this" is bound to data
});

var rules = { "and" : [
  {"<" : [ { "var" : "temp" }, 110 ]},
  {"in" : ["apple", { "var_search" : "pies.*.filling" } ] }
] };

var data = { "temp" : 100, "pies" : [{ "filling" : "apple" }, { "filling" : "cherry" }]};

jsonLogic.apply(rules, data);
// true

Does that work?

internalfx

internalfx commented on Feb 28, 2017

@internalfx

Had the same problem.

This is a common use case, and should be added to core.

@jwadhams thank you for the solution.

internalfx

internalfx commented on Feb 28, 2017

@internalfx

@PaulKruger please see #25

yarnball

yarnball commented on Jan 30, 2018

@yarnball

Thanks for your example above.

I am trying to filter on multiple nested fields. However, it isn't returning any results. Any suggestions?

var rules = { "and" : [
  {"<" : [ { "var" : "temp" }, 110 ]},
  {"in" : ["apple", { "var_search" : "pies.*.filling" } ] },
  {"in" : [10, { ">" : "pies.*.score" } ]}
] };

var data = { "temp" : 100, "pies" : [{ "filling" : "apple", "score": 10 }, { "filling" : "cherry", "score": 7 }]};

jsonLogic.apply(rules, data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @internalfx@jwadhams@PaulKruger@yarnball

        Issue actions

          Arrays with Objects · Issue #17 · jwadhams/json-logic-js