【问题标题】:How to remove key based on condition in array object javascript如何根据数组对象javascript中的条件删除键
【发布时间】:2020-05-20 09:33:30
【问题描述】:

我想知道如何删除对象数组 javascript 中的特定键。 在数组对象obj中,如果id为null,则删除javascript中的键

var obj = [{
  id: 1,
  field: "finance"
}, {
  id: null,
  field: "service}, {
  id: 2,
  field: "information"
}]

functionremoveKey(arrobj) {
  return arrobj.filter(e => {
    if (e.id == null) {
      delete e.id;
    }
  }
}

var result = removeKey(obj);

预期输出:

{
  { id: 1, field: "finance" },
  { field: "service" },
  { id: 2, field: "information" }
]

【问题讨论】:

  • 这不是.filter() 的用途。你要么想要.forEach() 要么 .map()
  • 您在service 之后缺少报价。是不是笔误?
  • 试试这个obj.forEach(e => { if (e.id === null) { delete e.id } });

标签: javascript jquery arrays object


【解决方案1】:

您可以为此使用map

var obj = [{ id: 1, field: "finance"}, { id: null, field: "service"}, { id: 2, field: "information"}]
result = obj.map(val=>val.id ? val : (delete val.id, val));
console.log(result);

【讨论】:

    【解决方案2】:

    正如Andreas 提到的,您需要遍历元素并删除键,而不是尝试过滤整个数组。像下面这样的东西会起作用:

    var arr = [
        { id: 1, field: "finance" },
        { id: null, field: "service" },
        { id: 2, field: "information" }
    ];
    
    function removeKey(arr) {
        arr.forEach(element => {
            if (element.id == null) {
                delete element.id;
            }                
        });
    }
    
    removeKey(arr);
    console.log(arr);
    

    【讨论】:

      【解决方案3】:

      如果你不想改变源,你可以使用以下:

      var obj = [{
        id: 1,
        field: "finance"
      }, {
        id: null,
        field: "service"
      }, {
        id: 2,
        field: "information"
      }]
      
      function removeKey(arrobj, keyname) {
        return arrobj.map(e => 
          Object.fromEntries(
            Object.entries(e).filter(
              ([k, v]) => v !== null || keyname !== k
            )
          )
        )
      }
      
      console.log(removeKey(obj, 'id'));

      它使用了Object.fromEntries方法,比较新,如果你的环境不支持,可以改用这个:

      var obj = [{
        id: 1,
        field: "finance"
      }, {
        id: null,
        field: "service"
      }, {
        id: 2,
        field: "information"
      }]
      
      function removeKey(arrobj, keyname) {
        return arrobj.map(e => 
          Object
            .entries(e)
            .filter(([k, v]) => v !== null || keyname !== k)
            .reduce((obj, [k, v]) => (obj[k] = v, obj), {})
        )
      }
      
      console.log(removeKey(obj, 'id'));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-02
        • 2017-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-02
        相关资源
        最近更新 更多