获取数组内部数组的问题

Porblem on Getting Array Inside of Array

我在数组内部的对象上遇到问题,我只想将其显示为数组。

data1

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

预期输出

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

代码

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

通过数组映射并提取其details 属性:

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)

map 遍历数组并 return 使用细节 属性 的新对象 。如果您不 return 一个新对象,您的新数组仍将包含对原始数组中对象的引用。因此,如果您更改原始数组中 属性 的值,该更改也会反映在新数组中,您可能不希望这种情况发生。

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

使用 map 和解构将简化。

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

const res = data1.map(({ details: { data } }) => ({ data }));

console.log(res);

// if you just need the details object

const res2 = data1.map(({ details }) => details);

console.log(res2);