如何提取对象中的某些项目?

时间:2019-03-26 06:43:22

标签: javascript arrays object

我正在尝试从一个对象中提取一些项目。如果我没看错,则需要使用for ... in来循环对象项目。

let myObject = {
  id: 1,
  company: "Apple",
  product: {
    name: "iPhone",
    price: "100",
    releaseDate: "01 Jan 2019",
    color: {
      black: "#000000",
      silver: "#C0C0C0",
    }
  }
}
for (property in myObject) {
  console.log(`${property} = ${myObject[property]}`);
}

我如何只获得product的{​​{1}}和name

预期结果:

price

1 个答案:

答案 0 :(得分:2)

您只需要Destructuring_assignment

let myObject = {
  id: 1,
  company: "Apple",
  product: {
    name: "iPhone",
    price: "100",
    releaseDate: "01 Jan 2019",
    color: {
      black: "#000000",
      silver: "#C0C0C0",
    }
  }
}


const {name, price} = myObject.product

console.log({name, price})

如果myObject是一个像@Hasan Sh提到的对象数组。您可以使用reduce

let myObject = [
  {
  id: 1,
  company: "Apple",
  product: {
    name: "iPhone",
    price: "100",
    releaseDate: "01 Jan 2019",
    color: {
      black: "#000000",
      silver: "#C0C0C0",
    }
  }
},
{
  id: 2,
  company: "Samsung",
  product: {
    name: "galaxy S9",
    price: "100",
    releaseDate: "01 Jan 2019",
    color: {
      black: "#000000",
      silver: "#C0C0C0",
    }
  }
}

]

const rs = myObject.reduce((acc, e) => {
  const {name, price} = e.product
  acc.push({name, price})
  return acc
}, [])




console.log(rs)