Javascript嵌套数组仅保留特定键

时间:2018-12-14 18:54:24

标签: javascript arrays

我有一个像这样的Javascript数组,只想保留白名单中的键:

<?php
    $file = $_FILES['file']['size'];
    echo $file;
    JS Code

    var text = document.getElementById('text');
    var input_f = document.getElementById('input_f');//Input file

    var xmlhttp = new XMLHttpRequest();
    var formData = new FormData();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            text.innerHTML = this.response;
        }
    };
    xmlhttp.open("POST","php/convert.php");
    formData.append('file', input_f.files[0]);
    xmlhttp.send(formData);

如何在不幼稚地解析数组和构造新的结果数组的情况下从此数组中删除所有未列入白名单的键?它不必是一成不变的操作,我更喜欢代码的可读性。

谢谢您的想法!

1 个答案:

答案 0 :(得分:0)

下面是一个可行的解决方案:

let arr = [
  { keep1: 'abc', keep2: 'def', buh1: false, buh2: false },
  { keep3: 'abc', keep4: 'def', buh3: false, buh4: true },
  { keep5: 'abc', keep6: 'def', buh5: false, buh5: false }
]

let whiteList = ['keep1', 'keep2', 'keep3', 'keep4', 'keep5'];

arr.forEach(function (obj) {
  Object.keys(obj).forEach(function(key) {
    if (whiteList.indexOf(key) == -1) 
      delete obj[key]
  })
})

console.log(arr)