Home > other >  Javascript Filter Array of Objects by Dynamic Key
Javascript Filter Array of Objects by Dynamic Key

Time:03-22

I'm starting with an array of objects, such as

const data = [
        {
          data1: 124,
          data2: 5332,
          data3: 12,
        },
        {
          data1: 642,
          data2: 5,
          data3: 798,
        }
     ]

I would like to filter the array of objects down to just the "data2" key, like this...

[
        {
          data2: 5332
        },
        {
          data2: 5,
        }
     ]

I tried with this code:

const key = "data2";
const filtered = data.filter((d) => Object.keys(d.data) === key )

And have tried variants of this filter. I know I can use data.forEach but was wondering if there is any way to accomplish this using filter

CodePudding user response:

What you want is

const filtered = data.map((d) => ({
  [key]: d[key]
}));

Working snippet:

const data = [{
    data1: 124,
    data2: 5332,
    data3: 12,
  },
  {
    data1: 642,
    data2: 5,
    data3: 798,
  }
]

const key = "data2";
const filtered = data.map((d) => ({
  [key]: d[key]
}));

console.log(filtered);

  • Related