Search code examples
javascriptarraysfilteringjavascript-objects

js: How to filter object keys from an array of objects?


I have an array similar to this one

let array = [
  {
    name: "1-name",
    age: 18,
    direction: "jsjs"
    phone: 7182718
  },
  {
    name: "2-name",
    age: 38,
    direction: "jsjsjs"
  },
  {
    name: "3-name",
    age: 58,
    direction: "jsjsjsjs"
  }
]

and i want to filter it based on its keys to get an array like this

[
  {
    name: "1-name",
    direction: "jsjs"
  },
  {
    name: "2-name",
    direction: "jsjsjs"
  },
  {
    name: "3-name",
    direction: "jsjsjsjs"
  }
]

Can you please help me i've try to solve it with no success


Solution

  • You can you the array map function.

    See an example here:

    const arr = [
       {
          name: "1-name",
          age: 18,
          direction: "jsjs",
          phone: 7182718
      },
      {
          name: "2-name",
          age: 38,
          direction: "jsjsjs",
          phone: 7182718
      },
      {
         name: "3-name",
         age: 58,
         direction: "jsjsjsjs",
         phone: 7182718
      }
    ]
    
    const result = arr.map(({ name, direction }) => {
     return {
        name, 
        direction
     };
    })
    
    console.log(result);