Home > Net >  Porblem on Getting Array Inside of Array
Porblem on Getting Array Inside of Array

Time:11-12

I have a problem on an object inside of an array and I wanted to display only that as an array.

data1

const data1 = [
  {
    "id": "01",
    "info": "fefef",
    "sub": "hieei",
    "details": {
      "data": "fruits"
    }
  },
  {
    "id": "02",
    "info": "fefef",
    "sub": "hieei",
    "details": {
      "data": "things"
    }
  }
]

expected output

const final= [
  {
    "data": "fruits"
  },
  {
    "data": "things"
  }
]

Code

 const final = data.map((data) => { ...data}) 

CodePudding user response:

Map through the array and extract its details property:

const data1 = [
  {
    "id": "01",
    "info": "fefef",
    "sub": "hieei",
    "details": {
      "data": "fruits"
    }
  },
  {
    "id": "02",
    "info": "fefef",
    "sub": "hieei",
    "details": {
      "data": "things"
    }
  }
]

const res = data1.map(e => e.details)

console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

map over the array and return a new object using the details property. If you don't return a new object, your new array will still carry references to the objects in the original array. So if you change a value of a property in that original array, that change will be reflected in the new array too, and you probably don't want that to happen.

const data1=[{id:"01",info:"fefef",sub:"hieei",details:{data:"fruits"}},{id:"02",info:"fefef",sub:"hieei",details:{data:"things"}}];

// Make sure you return a copy of the
// details object otherwise if you change the details
// of the original objects in the array
// the new mapped array will carry those object changes
// because the array objects will simply references to the old objects
const out = data1.map(obj => {
  return { ...obj.details };
});

console.log(out);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related