Adding element if doesn't exist and if it does exist change its value | code doesn't work |

An example of how the array looks like:
[{id:1,quantity:3},{id:2,quantity:4},{id:3,quantity:1}]

    handleOnClick(id, quantity) {

        let newArr = [...this.state.arr];
        let found = false;

        newArr.forEach(function (element) {

            if (element["id"] === id) {
                found = true;
                element["quantity"] = quantity;
            }
        });

        if (!found) {
            newArr.push({ "id": id, "quantity": quantity })
        }

           this.setState({ arr: newArr })
    }

i don’t know why it doesn’t work.

Does that not work for you?

This wouldn’t work anyway…

var index = newArr["id"].indexOf(id);
        if (index !== -1) {
            newArr[index]["id"] = id;
        } else {
            newArr.push({ "id": id, "quantity": quantity });
        }

Well it it’s an multidimensional array, you can simply access the sub arrays at whatever row you like and push it.

newArr[index].push({“id”: id, “quantity”:quantity})

1 Like
        let newArr = [...this.state.arr];
        let found = false;

        newArr.forEach(function (element) {

            if (element["id"] === id) {
                found = true;
                element["quantity"] = quantity;
            }
        });

        if (!found) {
            newArr.push({ "id": id, "quantity": quantity })
        }

           this.setState({ arr: newArr })

Doesn’t work

Update arr (this.state.arr)

What do you mean by update it with?
Right now I trying to show the array by using {this.state.arr} in the last return.

,Some minutes later

I finally got what you meant now.
I am getting the target id and the target quantity as expected, I tried only pushing the id and the quantity in the array before and it worked fine but what it did was only pushing every time I clicked the button so I got it to display for example 11 (id:1,quantity:1) when I clicked the first button then 1121 when I clicked the second one and 112131 the third one, if I changed the quantity of the first for example I would get 11213114.(if the quantity was 4)

You’re absolutely right but I though it wasn’t necessary because I guessed the problem was in the handleOnClick

I didn’t figure it out actually, it doesn’t work yet.

To be honest the post was posted by mistake without me wanting to but I left it as it was because the wiFi didn’t work. Then I didn’t give it much importance later and I tried to find a way by myself. I will try to make a jsfiddle of what I want to see if I find a solution that works.

{JSON.stringify(this.state.arr)}
That’s it.

I was getting [object Object],[object Object]

:sweat_smile::sweat_smile::sweat_smile::sweat_smile::sweat_smile::sweat_smile:

Thank you for your help.

It makes me feel stupid, I would have solved the problem just by doing the console.log of this.state.arr and understand what I was getting.