0

I have a JSON file with objects like this:

[
    {
        "name" : "something",
        "brand": "x",
        "category" : "cars"
    },
    {
        "name" : "something2",
        "brand": ["x", "y"],
        "category" : "bikes",
    }
]

To filter by category I do this:

filterObjects(key, value) {
    if (key == 'category') {
        objects.filter(item => item.category == value);
    }
}

But when I try to do this with brand, it only returns the first one.

How can I do to make my filter loop over each value and return both items?

Nacho
  • 69
  • 5
  • 1
    Please specify your intended output after filtering. – kmoser Nov 20 '20 at 04:48
  • Duplicate of [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript). Your question boils down to `item.brand == [ "x", "y" ]` always being `false`, because that’s not how arrays can be compared. The solution depends on what `value` you’re trying to make your code work with. – Sebastian Simon Nov 20 '20 at 04:49

3 Answers3

0

I think you should check first whether the field has array value or not:

const filterObjects = (key, value) => {
  return objects.filter(item => {
    // you can access a field of object this way too.
    const itemValue = item[key];

    // check if the field is an array
    if (Array.isArray(itemValue)) {
      
      // if array, the predicate becomes whether the array contains the value or not
      return itemValue.includes(value);

    // otherwise you can compare the value
    // I recommend you to use === operator rather than == operator
    } else {
      return itemValue === value;
    }
  });
};
Hyunwoong Kang
  • 530
  • 2
  • 9
0

It's not clear what your intended output is, but assuming you're trying to search for objects containing a given key/value pair:

// key and value to search for:
function filterObjects( key, value ) {
    var r = [];
    objects.forEach( function(obj) {
        if ( obj[key] == value ) {
            r.push( obj );
        }
    })

    return r;
}

let a = filterObjects( 'category', 'bikes' );
kmoser
  • 8,780
  • 3
  • 24
  • 40
0

I'm guessing you're trying to do the following where value === "x":

filterObjects(key, value) {
    if (key == 'brand') {
        objects.filter(item => item.brand == value);
    }
}

For the first element (element [0]), your item.brand === value check becomes "x" == "x" which is true, therefore it passes. But for the element [1], it becomes ["x", "y"] == "x" which is obviously false, so it doesn't pass.

You should probably write a comparison function that returns true when the two values are equal or when the first value is an array that includes the second one and use that function instead of a == check.

cyco130
  • 4,654
  • 25
  • 34