2

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

4 Answers 4

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.