简体   繁体   English

通过数组索引向数组中的特定对象添加值

[英]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 ?如何通过index将特定object值添加到array

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)我写了这个,但当然,它在array创建了一个新object ,但我想将“错误”插入到具有index的现有object (在屏幕上它为 0 索引)

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它向object插入一个值,但没有名称,它仍然在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
    }
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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