Javascript 为对象数组创建新属性时,对象不可扩展错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45798885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:13:18  来源:igfitidea点击:

Object is not extensible error when creating new attribute for array of objects

javascriptreactjs

提问by Mendes

I have a function that needs to extend a javascript array, including a new attribute called selected:

我有一个需要扩展 javascript 数组的函数,包括一个名为 的新属性selected

export const initSelect = (data) => {

    let newData = data.concat();
    newData.map((item) => {
        item.selected = false;
    })

    return newData;
}

datais a ReactJS state value (comes from this.state.datawhen calling the function), but this didn't seem to be a problem as newDatais a new copy of dataarray...

data是一个 ReactJS 状态值(来自this.state.data调用函数时),但这似乎不是问题,因为newDatadata数组的新副本......

I'm getting the following error:

我收到以下错误:

TypeError: Cannot add property selected, object is not extensible

回答by Jonas Wilms

You probably need to copy the objects:

您可能需要复制对象:

export const initSelect = (data) => {
 return data.map((item) => ({
     ...item,
     selected: false       
 }));
}

回答by lilezek

You can not extend itemwith selectedproperty, and your array is just a shallow copy.

你不能itemselected属性扩展,你的数组只是一个浅拷贝。

If you want to be able to extend, you will have to do a deep copy of your array. It may be enough with:

如果您希望能够扩展,则必须对数组进行深度复制。这可能就足够了:

let newData = data.map((item) => 
    Object.assign({}, item, {selected:false})
)

回答by Omar

const newObj = Object.assign({selected: false}, data);

const newObj = Object.assign({selected: false}, data);