-3

I'm trying to extract some of the items from an object. If I'm not wrong, I need to use for...in to loop the object items.

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]}`);
}

How can I only get the product's name and price only?

Expected result:

newArray = [
    name: "iPhone",
    price: 100,
]
mplungjan
  • 169,008
  • 28
  • 173
  • 236
pizza0502
  • 313
  • 6
  • 21

1 Answers1

2

What you need is just 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})

In case myObject is an array of object like @Hasan Sh mentioned. You can use 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)
bird
  • 1,872
  • 1
  • 15
  • 32
  • 1
    OR const {product:{name, price}} = myObject – AZ_ Mar 26 '19 at 06:54
  • 1
    I think what he meant is that the `myObject` is an object within an array?! `e.g. const data = [myObject, ...];` In that case loop through the `data` array and do TamDc's solution. – Hasan Sh Mar 26 '19 at 06:55