0

I have this object:

const data = { theValues: [ 
    {key1: "valueOne",
     key2: "someValue"}, 
    {key1:  "valueTwo",
     key2: "moreValue"}]}; 

If i use the following:

data.theValues = data.theValues.filter(obj => obj.key1 != 'valueOne');

I get this as result:

 const data = { theValues: [ 
    {key1:  "valueTwo",
     key2: "moreValue"}]};

Ok and thats what I wanted too. But if I have the this object:

 const data = { theValues: [ 
     {key1:  ["valueOne", "valueTwo"],
      key2: "otherValue"},    
     {key1:  ["valueThree","valueFour"],
      key2: "noValue"}]};

And I use the same thing:

data.theValues = data.theValues.filter(obj => obj.key1 != 'valueOne');

Nothing happens. Why is that and how can I delete the object with the value 'valueOne'?

Gabriel
  • 43
  • 5
  • It's because in the first example `key1` is a `string` property, whilst in the second example `key1` is an `array` property. You should also [consider using `!==` instead of `!=`](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons), if you don't have a specific use case for the `!=` operator. – Kapobajza Jan 12 '21 at 14:00

3 Answers3

2

Since the value of key is an array, you can't compare it to a string - obj.key1 != 'valueOne' is always true. Check the array doesn't include the term (valueOne) using Array.includes():

const data = {"theValues":[{"key1":["valueOne","valueTwo"],"key2":"otherValue"},{"key1":["valueThree","valueFour"],"key2":"noValue"}]};

const result = data.theValues.filter(obj => !obj.key1.includes('valueOne'));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

It's not working because you are comparing array with string. Here, key1 is an array and valueOne is string. You could use Array.prototype.filter() with Array.prototype.some() method. Filter array where key1 does not contain valueOne.

Some method returns true if at least one element in the array passes the test.

const data = {
  theValues: [
    { key1: ['valueOne', 'valueTwo'], key2: 'otherValue' },
    { key1: ['valueThree', 'valueFour'], key2: 'noValue' },
  ],
};
const ret = data.theValues.filter((x) => !x.key1.some((y) => y === 'valueOne'));
console.log(ret);
mr hr
  • 3,162
  • 2
  • 9
  • 19
0

It happens because key1 is array, not key of object. So you can use indexof method to get desired result:

const result = data.theValues.filter(obj => obj.key1.indexOf('valueOne'));

An example:

const data = { "theValues":
    [
          { "key1": ["valueOne", "valueTwo"], "key2": "otherValue" }
        , { "key1": ["valueThree", "valueFour"], "key2": "noValue" }
    ]
};



const result = data.theValues.filter(obj => obj.key1.indexOf('valueOne'));

console.log(result);
StepUp
  • 36,391
  • 15
  • 88
  • 148