Deepika Deepi
Deepika Deepi

Reputation: 127

Delete an object from an array based on the value of the dynamic property names

I have the following array of objects which needs to be filtered based on the values but the problem is the property name is dynamic.

const data = [
  {id: 112, cat: 0, dog: 0},
  {id: 114, cat: 0, dog: 1},
  {id: 115, tiger: 5, dog: 0},
  {id: 116, tiger: 0, lion: 3},
  {id: 117, tiger: 0, lion: 0}
];

My desired output should be as follows:

const output = [
   {id: 114, cat: 0, dog: 1},
   {id: 115, tiger: 5, dog: 0},
   {id: 116, tiger: 0, lion: 3}
];

The situation here is i have id as a constant property. But the other two property name changes. If the value of both the properties (excluding id property) is 0 in an object, then that object should be deleted.

Upvotes: 1

Views: 55

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could destructure unwanted properties and take the values from the rest and check if some value is truthy.

const
    data = [{ id: 112, cat: 0, dog: 0 }, { id: 114, cat: 0, dog: 1 }, { id: 115, tiger: 5, dog: 0 }, { id: 116, tiger: 0, lion: 3 }, { id: 117, tiger: 0, lion: 0 }],
    result = data.filter(({ id, ...o }) => Object.values(o).some(Boolean));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

MauriceNino
MauriceNino

Reputation: 6747

You can do it with a combination of filter() and every()

const data = [
  {id: 112, cat: 0, dog: 0},
  {id: 114, cat: 0, dog: 1},
  {id: 115, tiger: 5, dog: 0},
  {id: 116, tiger: 0, lion: 3},
  {id: 117, tiger: 0, lion: 0}
];

// Every key/value pair in object that is named id OR has a 0 value is filtered out
const result = data.filter(d => 
      !Object.entries(d)
             .every(([key, value]) => key == 'id' || value == 0)
);

console.log(result);

Upvotes: 2

Related Questions