Search code examples
javascriptarraysobjectecmascript-6ecmascript-2016

Porblem on Getting Array Inside of Array


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}) 

Solution

  • 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);