0

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

3 Answers3

3

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);
michaelitoh
  • 2,317
  • 14
  • 26
-1

You Can Try This Code:

let newArr = [];

array.forEach((e) => {
  newArr.push({ name: e.name, direction: e.direction });
});
-1

The map method will work. How you implement this depends on whether you want to create a new array result with the previous objects deleted, or simply return the ones you want to keep. This will create a new array your original array will remain unaffected.

array.map(function (result) {
  delete result.age;
  delete result.phone;
});
console.log(result)