【问题标题】:Deleting a list of keys删除键列表
【发布时间】:2015-01-01 21:12:33
【问题描述】:

在 Javascript 中,我有一个对象,我希望删除多个键:

x = {"id":2,"user_id":1,"name":"document_name","description":"the  document","file_type":null,"file_id":null}
delete x.file_type
delete x.file_id

结果:

Object {id: 2, user_id: 1, name: "document_name", description: "the document"}

我宁愿在一个命令中删除所有键,也许传递一个键数组?
或者,使用某种类型的下划线/lodash 过滤器来实现相同的目标。

【问题讨论】:

    标签: javascript underscore.js lodash


    【解决方案1】:
    ['file_type', 'file_id'].forEach(function (key) {
      delete x[key];  
    });
    

    演示:http://jsbin.com/vevotu/1/

    【讨论】:

      【解决方案2】:

      使用下划线,您可以使用_.omit 排除不必要的键:

      _.omit(x, 'file_type', 'file_id');
      

      但是请注意,omit 返回对象的副本。所以和使用delete运算符不一样。

      查看下面的演示。

      var x = {"id":2,"user_id":1,"name":"document_name","description":"the  document","file_type":null,"file_id":null};
      var result = _.omit(x, 'file_type', 'file_id');
      
      alert(JSON.stringify(result, null, 4));
      <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2012-08-05
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 2018-10-07
        相关资源
        最近更新 更多