0

I am trying do loop over a prop and push the parent and child to a variable. I seem to be able to get the looping and pushing working correctly, but its pushing all the children under each parent

var options = [];
    var option = [];
    Object.keys(this.props.data.options).forEach((key, index) => {
      options.push(
        <AddToCartRow key={index} option={key} options={option} cartKey={this.props.cartKey} />,
        Object.values(this.props.data.options[key]).forEach((value, index) => {
          option.push(value)
        })
      )
    })

Below is what is currently happening

enter image description here

The expected result should be

size - 0[price: 3.95, title: Small] - 1 [price: 4.95, title: Large]

blend - 0[price: 0, title: Regular] - 1 [price: 0, title: Decaf]

etc

1 Answer 1

2

It seems you have problem with pushing element into array. I have managed by doing as below

for (let parentData of mainObj) {
    let tempArray = []; // need to declare here
    for (let childData of parentData.someField) {
        tempArray.push({
            ...
        });
    }
    finalArray.push(tempArray);
}

You need to push your child loop data into temporary array and then to main resultant array which is options in your case .

Sign up to request clarification or add additional context in comments.

2 Comments

isnt this what I am doing already I have the child loop within the primary loop
yes it is similar,the only difference is var option = []; declared above, I have used in before child loop. So each time it will be created as new array and append to primary loop

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.