How to extract array of objects using interface

96 Views Asked by At

I have an array of objects with large amount of data like This is the example data but I am having large amount of key pair values

 [{ "id": 1, "name":"name1", age: 11,   "skl": {"name": "KK school"} },
    { "id": 2, "name":"name2", age: 12, "skl": {"name": "KK school"} },
    { "id": 3, "name":"name3", age: 13, "skl": {"name": "KK school"} },
    { "id": 4, "name":"name4", age: 14, "skl": {"name": "KK school"} } ]

I need only id and name and skl name like.

 [  { "id": 1, "name":"name1", "skl": {"name": "KK school"},
    { "id": 2, "name":"name2", "skl": {"name": "KK school"},
    { "id": 3, "name":"name3", "skl": {"name": "KK school"},
    { "id": 4, "name":"name4", "skl": {"name": "KK school"} ]

How to extract from these array of objects is there any possible solution

2

There are 2 best solutions below

2
On

You can either specify the properties you want to keep, or specify the properties you want to remove:

const data = [
{ "id": 1, "name":"name1", age: 11, "skl": {"name": "KK school"} },
{ "id": 2, "name":"name2", age: 12, "skl": {"name": "KK school"} },
{ "id": 3, "name":"name3", age: 13, "skl": {"name": "KK school"} },
{ "id": 4, "name":"name4", age: 14, "skl": {"name": "KK school"} } ]

// choose what you want to retain:
console.log(data.map(({id, name, skl})=>({id, name, skl})))

// choose what you want to drop:
console.log(data.map(({age, ...other})=>other))

// dynamically:
console.log(data.map(i=>Object.fromEntries(Object.entries(i)
  .filter(([k])=>['id','name','skl'].includes(k)))))

0
On

Map through array and and extract age from reset array and returning rest shown data without age key

  data.map(({age,...reset}) => reset) //map return a new array