V
V
Vladislav2017-07-06 00:26:59
underscore.js
Vladislav, 2017-07-06 00:26:59

Difference between arrays of objects by underscore key?

Hello. Something does not work to get the difference between 2 arrays of objects by key field.
There are 2 arrays of objects.
one:

[
  {
        "name": "name1",
        "prices": [
            {
                "count": 15164,
                "price": 0.34,
            }
        ],
    },
    {
        "name": "name2",
        "prices": [
            {
                "count": 26606,
                "price": 0.33,
            },
      {
                "count": 266,
                "price": 0.23,
            }
        ],
    },
    {
        "name": "name3",
        "prices": [
            {
                "count": 0,
                "price": 0.45,
            }
        ]
    },
  {
        "name": "name4",
        "prices": [
            {
                "count": 1,
                "price": 0.45,
            }
        ]
    }
]

and second:
[
  {
        "name": "name1",
        "prices": [
            {
                "count": 26019,
                "price": 1.13,
            }
        ]
    },
    {
        "name": "name2"
    },
    {
        "name": "name3",
        "prices": [
            {
                "count": 3198,
                "price": 1.05,
            },
            {
                "count": 3513,
                "price": 0.94,
            }
        ]
    }
]

And you need to subtract the second from 1 array of objects if the name field matches. That is, by subtracting arrays, we must get an array from an object whose name was not in the 2nd array:
[
  {
        "name": "name4",
        "prices": [
            {
                "count": 1,
                "price": 0.45,
            }
        ]
    }
]

I already tried both _difference and _where, _findWhere, but arrays are input there and it is not possible to specify the key. It is necessary to do it through a loop and _find (or through a filter?), Kind of like, but I can’t compose the condition correctly.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2017-07-08
@vlad00777

Made in lodash.
_.differenceBy(arr1, arr2, 'name');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question