3

How to add value to a specific object to the array by the index?

I wrote this, but of course, it creates a new object in the array, but I want to insert "errors" to an existing object with index (on screen it 0 index)

ipcRenderer.on('fileData', (event, data) => {
    this.setState({jobs: [...this.state.jobs, {errors: data}]})
});

screen

Then i wrote this:

ipcRenderer.on('fileData', (event, data) => {
    this.state.jobs.forEach((item, index) => {
        this.setState({jobs: [...this.state.jobs, {errors: item[index] = data}]
    })
    console.log(this.state)
    })
});

It inserts a value into the object, but without a name and it still creates a new element in the array

enter image description here

I want the result to be like this:

jobs: [
    0: {errors: 10, fileName:...}
]
0

3 Answers 3

2

If you know the index, you can just do

const jobs = this.state.jobs.slice(0);
jobs[index].errors = data;
this.setState({jobs});

Might have to do more than slice the array, might have to make a deep copy, but yeah, that should work.

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

Comments

1

Firstly you can make a copy of your array like

let jobsCopy = this.state.jobs

Then if you know the index you could just do like

jobsCopy[index].errors = 10
this.setState({
    jobs: jobsCopy
})

Comments

0

You would need to know the index of the object you want to change. For example if you know it is the first item in the array you can do this:

const indexToChange = 0
this.setState(prevState => prevState.map((obj, i) => {
    if(i === indexToChange) {
        return {
            ...obj,
            errors: data
        }
    } else {
        return obj
    }
}))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.