“对象不可扩展”错误尝试在地图功能中添加字段

时间:2018-02-28 04:37:43

标签: javascript

我尝试使用map:

为数组中的项添加新字段
const newArray = oldArray.map(item => {
    return (item.newField = 'Something');
});

我试过了:

const newArray = oldArray.map(item => {
    item.newField = 'Something';
    return item;
});

但是我收到错误:

TypeError: Cannot add property newField, object is not extensible

4 个答案:

答案 0 :(得分:2)

您可以像这样使用对象传播(es6功能):

const newArray = oldArray.map(item => {
    // { ...item } creates a new object and spreads all of "item" items
    // into it. We can then assign a "newField" or overwrite "newField" 
    // if it already exists on "item"
    return { ...item, newField: 'something' };
});

答案 1 :(得分:0)

const newArray = oldArray.map(item => {
    const newItem =  Object.assign({}, item, { newField: 'Something' });
    return newItem;
});

答案 2 :(得分:0)

最有可能将Object标记为不可扩展,并且您正在运行严格模式。

查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible

调用方法Object.preventExtensions(obj)时,会出现错误。

'use strict';

var obj = {};
Object.preventExtensions(obj);

obj.x = 'foo';

您将收到错误Uncaught TypeError: Cannot add property x, object is not extensible

答案 3 :(得分:0)

或者,您也可以通过Object.create(...)

克隆对象
const object1 = {
  foo: 'foo'
};

// This will prevent extending this object:
Object.preventExtensions(object1);

const object2 = Object.create(object1);

/**
 * This cloned object has no preventExtensions flag
 * and can thus be extended as you like
 */
object2.bar = 'bar';