SilentKunZ
SilentKunZ

Reputation: 75

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

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:...}
]

Upvotes: 3

Views: 89

Answers (3)

Nipun Jain
Nipun Jain

Reputation: 1014

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

Upvotes: 1

Travis James
Travis James

Reputation: 1939

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

Upvotes: 0

TKoL
TKoL

Reputation: 13892

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.

Upvotes: 2

Related Questions