gpt4 book ai didi

javascript - 使用 Object.assign() 删除对象属性

转载 作者:行者123 更新时间:2023-11-29 20:52:08 25 4
gpt4 key购买 nike

是否可以使用 Object.assign() 删除键,而不是在以下示例中将值设置为 undefined

我正在使用 .filter() 来浏览一些项目。当匹配时,我想添加/更改 x 属性值并删除 y 和 z 属性(而不是将它们设置为未定义)。

files.forEach(file => {
this.setState({
items: this.state.items.filter(item => item.id === file.id ? Object.assign(item, { x: 'x', y: undefined, z: undefined }) : item)
});
})

最佳答案

不是,看看官方的 polyfill 做了什么,来自 MDN :

if (typeof Object.assign != 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}

var to = Object(target);

for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];

if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}

没有可以删除 key 的可利用功能。


您将需要一个明确的delete,例如:

const updateMatch = (item, file, add, unset) => {

if(item.id !== file.id)
return item;

unset.forEach(key => {

delete item[key];

});

return Object.assign(item, add);

}

files.forEach(file => {
this.setState({
items: this.state.items.filter(item => updateMatch(item, file, { x: 'x' }, ['y', 'z']))
});
})

关于javascript - 使用 Object.assign() 删除对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51373932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com