2

I have an array of objects with name and age property:

[
  { name: "Matthew", age: 23 },
  { name: "James", age: 20 }, 
  { name: "Daniel", age: 25 },
  { name: "Joshua", age: 22 }
]

I want to remove age property from all of the objects and print in console like

[
  { name: "Matthew" },
  { name: "James" }, 
  { name: "Daniel" },
  { name: "Joshua" }
]
Syscall
  • 19,327
  • 10
  • 37
  • 52
Samir
  • 91
  • 6

3 Answers3

3

Iterate over your array and use delete keyword.

let array = [
  { name: "Matthew", age: 23 },
  { name: "James", age: 20 }, 
  { name: "Daniel", age: 25 },
  { name: "Joshua", age: 22 }
]
array.forEach(function(v){ delete v.age });
console.log(array);
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
0

You can use map function to achieve this.

let output = test.map(({name}) => ({name}));

If you want to filter with multiple object you can add after name like {name, salary}

var test =[
  { name: "Matthew", age: 23 },
  { name: "James", age: 20 }, 
  { name: "Daniel", age: 25 },
  { name: "Joshua", age: 22 }
];
let output = test.map(({name}) => ({name}));
console.log(JSON.stringify(output, null, 2));
Suresh Ponnukalai
  • 13,820
  • 5
  • 34
  • 54
-1
const newData = oldData.map(item=>({name:item.name}))
Abdul Haseeb
  • 372
  • 1
  • 6
  • 2
    this way we have the problem that if the array object has other keys and the developer don't want to remove others, but only "age" property. Your solution will fail. – Riyaz Khan Mar 22 '21 at 06:11