Dylan L.
Dylan L.

Reputation: 1317

remove all key value pairs from array of objects except for a specific key value

I have an array of objects

const myArr = [
  {k1: 1, k2: 1, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}
]

I am trying to filter these, I don't need to use filter but that's just what I'm currently doing.

const filteredObj = myArr.filter(item => item.k2 === 1)

but I would like to only keep one key value pair. For example

console.log(myArr) => {k2: 1}

Upvotes: 0

Views: 54

Answers (1)

esqew
esqew

Reputation: 44693

Use map() with object destructuring and property shorthand syntax:

const myArr = [
  {k1: 1, k2: 1, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}
]

const filteredObj = myArr.filter(item => item.k2 === 1).map(({k2}) => ({k2}));

console.log(filteredObj);

Upvotes: 2

Related Questions