使用Object.assign()

时间:2018-07-17 05:39:24

标签: javascript node.js reactjs object

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

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

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) 
    });
})

3 个答案:

答案 0 :(得分:2)

不是,请查看MDN中的官方polyfill:

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
  });
}

没有可用来删除密钥的可利用功能。


您将需要一个明确的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'])) 
    });
})

答案 1 :(得分:0)

尝试如下

var jbt = {
    "name": "uday",
    "age": "25"
}
console.log("Before Change--->", jbt);
jbt = Object.assign({}, delete jbt.age, jbt);
console.log("Afetr Change--->", jbt);

控制台结果

Before Change---> { name: 'uday', age: '25' }
Afetr Change---> { name: 'uday' }

对于您的情况,请尝试如下

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

答案 2 :(得分:0)

虽然它不允许您通过Object.assign进行删除,但是您可以使用ES6销毁方法以一种清晰明了的方式来解决此问题:

let file = {id: 12}
let items = [
    {id: 1, x: 1, y:2, z: 13},
    {id: 12, x: 3, y:6, z: 23},
    {id: 13, x: 2, y:9, z: 33},
    {id: 14, x: 4, y:12, z: 43}
]
items = items.map(item => {
    let {y, z, ...obj} = item
    return item.id === file.id ? Object.assign(obj, { x: 'x'}) : item
}) 
console.log(items)