我正在尝试使用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发布于 2018-02-28 12:44:43
最有可能的情况是,对象被标记为不可扩展,并且您正在运行严格模式。
看看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant
当调用Object.preventExtensions(obj)方法时,您会得到错误。
'use strict';
var obj = {};
Object.preventExtensions(obj);
obj.x = 'foo';您将看到错误Uncaught TypeError: Cannot add property x, object is not extensible
发布于 2018-02-28 12:43:56
const newArray = oldArray.map(item => {
return Object.assign({}, item, { newField: 'Something' });
});发布于 2020-01-21 14:07:53
您可以按如下方式使用对象扩散(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' };
});https://stackoverflow.com/questions/49022068
复制相似问题