t56k
t56k

Reputation: 6981

Filter key from list of objects

How can I filter each key out from a list of objects in ES6? Given this original (there can be many in this list):

[{"x": 0, 
 "y": 0, 
 "width": 10, 
 "frame_variables": [{"lookup_type": null,"lookup_id": null}]
}]

I want to return this:

[{"x": 0, 
 "y": 0, 
 "width": 10
}]

I'm thinking something list this but I'm not sure on the syntax:

displayFrames: function () {
  return this.frames.filter(e => e.key !== 'frame_variables')
}

Any ideas?

Upvotes: 2

Views: 436

Answers (3)

Derek Pollard
Derek Pollard

Reputation: 7165

Something like this should do it:

let data = {
  "x": 0,
  "y": 0,
  "width": 10,
  "frame_variables": [{
    "lookup_type": null,
    "lookup_id": null
  }]
};

const filterAttribute = (obj, keyToFilterOut) => (Object.keys(obj)).reduce((filteredObj, key) => {
  if (keyToFilterOut !== key) {
    filteredObj[key] = obj[key]
  }
  return filteredObj;
}, {});

console.log(filterAttribute(data, 'frame_variables'))

My solution doesn't mutate the original object either, instead opting to create a new one altogether - great in case you want to keep the data for other reasons

Upvotes: 2

Matt
Matt

Reputation: 2213

Filtering is for removing entire elements from an array. You can just loop over the array and call delete for each one.

for (var i = 0, len = array.length; i < len; i++) {
    delete array[i].frame_variables;
}

Upvotes: 2

Gonzalo.-
Gonzalo.-

Reputation: 12672

let array = [{"x": 0, 
 "y": 0, 
 "width": 10, 
 "frame_variables": [{"lookup_type": null,"lookup_id": null}]
}];

let result = array.map(({ frame_variables, ...rest }) => ({ ...rest }));

console.log(result);

you need to use map function to transform all your elements from your array. With destructuring you can separate frame_variables key from the rest of the object, so you just return a new object without that key.

Upvotes: 4

Related Questions