Aidyn Ibrayev
Aidyn Ibrayev

Reputation: 77

How to get access to object which is in forEach Javascript

I want to access object named productData and its properties to push in array called lookedArray. How to get access to productData?

saveProductToRecent = () => {
this.props.data.forEach(element => {
  const productData = {
    productImg: JSON.parse(element.node.product.mediaUrl).images[0],
    productPrice: element.node.product.minimalPrice,
    productName: element.node.product.name,
    productOID: element.node.product.oid
  }
});

let lookedArray = []
lookedArray.push()
localStorage.setItem('items', lookedArray)
}

Upvotes: 2

Views: 52

Answers (4)

codejockie
codejockie

Reputation: 10844

You can use reduce for this instead of forEach.

saveProductToRecent = () => {
  const lookedArray = this.props.data.reduce((acc, element) => {
    const productData = {
      productImg: JSON.parse(element.node.product.mediaUrl).images[0],
      productPrice: element.node.product.minimalPrice,
      productName: element.node.product.name,
      productOID: element.node.product.oid
    };

    // Add productData to acc array
    return acc.concat(productData);
  }, []);

  localStorage.setItem('items', lookedArray);
}

Upvotes: 0

I Putu Yoga Permana
I Putu Yoga Permana

Reputation: 4220

Or you can use immutable approach by utilize .map to simplify the works.

saveProductToRecent = () => {
  const lookedArray = this.props.data.map(element => ({
    productImg: JSON.parse(element.node.product.mediaUrl).images[0],
    productPrice: element.node.product.minimalPrice,
    productName: element.node.product.name,
    productOID: element.node.product.oid
  });

  localStorage.setItem('items', lookedArray)
}

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281646

You just need to push productData to lookedArray inside the forEach loop

saveProductToRecent = () => {
    let lookedArray = [];

    this.props.data.forEach(element => {
      const productData = {
        productImg: JSON.parse(element.node.product.mediaUrl).images[0],
        productPrice: element.node.product.minimalPrice,
        productName: element.node.product.name,
        productOID: element.node.product.oid
      }
      lookedArray.push(productData);
    });

    localStorage.setItem('items', lookedArray)
}

Upvotes: 2

Tarun Dugar
Tarun Dugar

Reputation: 8971

Move the push statement inside the forEach and declare lookedArray before the forEach:

let lookedArray = []
saveProductToRecent = () => {
this.props.data.forEach(element => {
  const productData = {
    productImg: JSON.parse(element.node.product.mediaUrl).images[0],
    productPrice: element.node.product.minimalPrice,
    productName: element.node.product.name,
    productOID: element.node.product.oid
  }
  lookedArray.push(productData);
});

localStorage.setItem('items', lookedArray)
}

Upvotes: 0

Related Questions