0
let arr = [
  { name: "rick", age: "44", phone: "33434", address: "florida" },
  { name: "sam", age: "33", phone: "23232", address: "milan" }
]

I only want to show only name and age, like this:

let filteredArr = [
  { name: "rick", age: "44"},
  { name: "sam", age: "33"}
]
ubuntu7788
  • 115
  • 2
  • 10
  • 2
    What have you tried, and what exactly is the problem with it? You seem to want to *map*, not *filter*, the array; the output length is the same as the input length. – jonrsharpe Mar 31 '20 at 07:35

2 Answers2

1

With map

let arr = [
  { name: "rick", age: "44", phone: "33434", address: "florida" },
  { name: "sam", age: "33", phone: "23232", address: "milan" }
]

const newarr = arr.map(({name, age}) => ({name, age}))

console.log(newarr)

Based on https://stackoverflow.com/a/47916931/476951, you can do this dynamically

const arr = [
  { name: "rick", age: "44", phone: "33434", address: "florida" },
  { name: "sam", age: "33", phone: "23232", address: "milan" }
]

function filterMap (arr, fields) {
  return arr.map(el => 
    fields.reduce((a,c) => ({...a, [c]: el[c]}), {}))
} 

const newarr = filterMap(arr, ['name', 'age'])
console.log(newarr)
yunzen
  • 32,854
  • 11
  • 73
  • 106
0

In this case you map opt to use map instead of filter

let arr = [{
    name: "rick",
    age: "44",
    phone: "33434",
    address: "florida"
  },
  {
    name: "sam",
    age: "33",
    phone: "23232",
    address: "milan"
  }
]

let filteredData = arr.map(item => {
  return {
    name: item.name,
    age: item.age
  }

});

console.log(filteredData)
brk
  • 48,835
  • 10
  • 56
  • 78