Gabriel
Gabriel

Reputation: 43

delete object in array

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'?

Upvotes: 0

Views: 78

Answers (3)

phi-rakib
phi-rakib

Reputation: 3302

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);

Upvotes: 0

StepUp
StepUp

Reputation: 38209

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);

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 193248

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);

Upvotes: 2

Related Questions