简体   繁体   中英

add value to specific object in array by index of array

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

屏幕

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

在此处输入图片说明

I want the result to be like this:

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM