【问题标题】:How do I filter keys from JSON in Node.js?如何从 Node.js 中的 JSON 过滤键?
【发布时间】:2019-02-27 12:53:12
【问题描述】:

我正在尝试从 JSON 数组中选择某些键,然后过滤其余的。

var json = JSON.stringify(body);

这是:

{  
   "FirstName":"foo",
   "typeform_form_submits":{  
      "foo":true,
      "bar":true,
      "baz":true
   },
  "more keys": "foo",
  "unwanted key": "foo"
}

想要我想要的:

{  
   "FirstName":"foo",
   "typeform_form_submits":{  
      "foo":true,
      "bar":true,
      "baz":true
   }
}

我已经查看了 How to filter JSON data in node.js?,但我希望在没有任何包的情况下执行此操作。

【问题讨论】:

标签: node.js json


【解决方案1】:

现在你可以像这样使用Object.fromEntries

Object.fromEntries(Object.entries(raw).filter(([key]) => wantedKeys.includes(key)))

【讨论】:

    【解决方案2】:

    您需要在将 obj 传递给 json stringify 之前对其进行过滤:

    const rawJson = {  
       "FirstName":"foo",
       "typeform_form_submits":{  
          "foo":true,
          "bar":true,
          "baz":true
       },
      "more keys": "foo",
      "unwanted key": "foo"
    };
    
    // This array will serve as a whitelist to select keys you want to keep in rawJson
    const filterArray = [
      "FirstName",
      "typeform_form_submits",
    ];
    
    // this function filters source keys (one level deep) according to whitelist
    function filterObj(source, whiteList) {
      const res = {};
      // iterate over each keys of source
      Object.keys(source).forEach((key) => {
        // if whiteList contains the current key, add this key to res
        if (whiteList.indexOf(key) !== -1) {
          res[key] = source[key];
        }
      });
      return res;
    }
    
    // outputs the desired result
    console.log(JSON.stringify(filterObj(rawJson, filterArray)));

    【讨论】:

    • 我收到错误“filterObj 未定义”,但您的 sn-p 运行良好。有什么想法吗?
    • 没关系,得到下面的答案 - 我不确定是什么造成了不同!
    • 工作就像一个魅力,我可以将其扩展为具有键值对数组
    【解决方案3】:

    var raw = {  
       "FirstName":"foo",
       "typeform_form_submits":{  
          "foo":true,
          "bar":true,
          "baz":true
       },
      "more keys": "foo",
      "unwanted key": "foo"
    }
    var wantedKeys =["FirstName","typeform_form_submits" ]
    var opObj = {}
    Object.keys(raw).forEach( key => {
       if(wantedKeys.includes(key)){
        opObj[key] = raw[key]
     }
    })
    
    console.log(JSON.stringify(opObj))

    【讨论】:

      【解决方案4】:

      我知道有人问过这个问题,但我只想扔在那里,因为没有其他人这样做:

      如果您被绑定并决心使用stringify 执行此操作,则其鲜为人知的功能之一涉及replacer,它是第二个参数。例如:

      // Creating a demo data set
      let dataToReduce = {a:1, b:2, c:3, d:4, e:5};
      console.log('Demo data:', dataToReduce);
      
      // Providing an array to reduce the results down to only those specified.
      let reducedData = JSON.stringify(dataToReduce, ['a','c','e']);
      console.log('Using [reducer] as an array of IDs:', reducedData);
      
      // Running a function against the key/value pairs to reduce the results down to those desired.
      let processedData = JSON.stringify(dataToReduce, (key, value) => (value%2 === 0) ? undefined: value);
      console.log('Using [reducer] as an operation on the values:', processedData);
      
      // And, of course, restoring them back to their original object format:
      console.log('Restoration of the results:', '\nreducedData:', JSON.parse(reducedData), '\nprocessedData:', JSON.parse(processedData));

      在上面的代码sn-p中,键值对只使用stringify进行过滤:

      • 在第一种情况下,通过提供一个字符串数组,表示您希望保留的键(根据您的请求)
      • 其次,通过针对 运行一个函数,并动态确定要保留的那些(您没有请求,但它是同一属性的一部分,并且可能对其他人有所帮助)
      • 第三部分,它们各自转换回 JSON(使用 .parse())。

      现在,我想强调的是,我并不是在提倡将其作为减少对象的适当方法(尽管它会生成所述对象的干净 SHALLOW 副本,并且实际上具有令人惊讶的性能),即使只是从默​​默无闻/从可读性的角度来看,它是一个完全有效的(并且是主流的;也就是说:它内置在语言中,而不是 hack)选项/工具,可以添加到武器库中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        • 2020-08-22
        • 2021-12-26
        相关资源
        最近更新 更多