0

i need map object data with array

const data = [
              {name:"John", age:"22", weight:"60", height:"180cm"},
              {name:"Emma",age:"25",weight:"55",height:"160cm"}
             ]

const key =  ["name", "weight", "height"]

i need result like this

const result = [
                {name:"John", weight:"60", height:"180cm"},
                {name:"Emma", weight:"55",height:"160cm"}
               ]

Thanks for helping

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
Panudeth Jaruwong
  • 125
  • 1
  • 3
  • 9

1 Answers1

5

You can just map over each of the objects, and use Object.fromEntries to create a new object with the given keys:

const data = [
  { name: "John", age: "22", weight: "60", height: "180cm" },
  { name: "Emma", age: "25", weight: "55", height: "160cm" }
]
const keys = ["name", "weight", "height"]

const res = data.map(o => Object.fromEntries(keys.map(k => [k, o[k]])))
console.log(res)

It would be even better to use reduce instead of two loops, albeit less readable:

const data = [
  { name: "John", age: "22", weight: "60", height: "180cm" },
  { name: "Emma", age: "25", weight: "55", height: "160cm" }
]
const keys = ["name", "weight", "height"]

const res = data.map(o => keys.reduce((a, k) => (a[k] = o[k], a), {}))
console.log(res)
Kobe
  • 6,226
  • 1
  • 14
  • 35