如何在JavaScript中过滤JSON对象? [英] How can I filter a JSON object in JavaScript?

查看:128
本文介绍了如何在JavaScript中过滤JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON字符串:

I've got the following JSON string:

{
   "Alarm":{
      "Hello":48,
      "World":3,
      "Orange":1
   },
   "Rapid":{
      "Total":746084,
      "Fake":20970,
      "Cancel":9985,
      "Word": 2343
   },
   "Flow":{
      "Support":746084,
      "About":0,
      "Learn":0
   }
}

然后我加载上面的字符串并将其转换为json对象:

Then I load the above string and convert it to json object:

jsonStr = '{"Alarm":{"Hello":48,"World":3,"Orange":1},"Rapid":{"Total":746084,"Fake":20970,"Cancel":9985},"Flow":{"Support":746084,"About":0,"Learn":0}}';
var jsonObj = JSON.parse(jsonStr);

现在,如何按键名过滤此json对象?

Now, how can I filter this json object by key name?

例如,如果过滤器为"ange",则过滤后的对象为:

E.g., if the filter was "ange", the filtered object would be:

{
   "Alarm":{
      "Orange":1
   }
}

如果过滤器为"flo",则过滤后的对象将变为:

If the filter was "flo", the filtered object would become:

{
   "Flow":{
      "Support":746084,
      "About":0,
      "Learn":0
   }
}

如果过滤条件为"wor",则结果为:

And if the filter was "wor", the result would be:

{
   "Alarm":{
      "World": 3,
   },
   "Rapid":{
      "Word": 2343
   }
}

是否可以使用filter方法实现此过滤?

Is it possible to achieve this filtering using the filter method?

推荐答案

您可以使用reduce()Object.keys()创建一个函数,该函数将使用indexOf()检查键名并返回所需的结果.

You can create a function using reduce() and Object.keys() that will check key names with indexOf() and return the desired result.

var obj = {
  "Alarm": {
    "Hello": 48,
    "World": 3,
    "Orange": 1
  },
  "Rapid": {
    "Total": 746084,
    "Fake": 20970,
    "Cancel": 9985,
    "Word": 2343
  },
  "Flow": {
    "Support": 746084,
    "About": 0,
    "Learn": 0
  }
}

function filterBy(val) {
  var result = Object.keys(obj).reduce(function(r, e) {
    if (e.toLowerCase().indexOf(val) != -1) {
      r[e] = obj[e];
    } else {
      Object.keys(obj[e]).forEach(function(k) {
        if (k.toLowerCase().indexOf(val) != -1) {
          var object = {}
          object[k] = obj[e][k];
          r[e] = object;
        }
      })
    }
    return r;
  }, {})
  return result;
}

console.log(filterBy('ange'))
console.log(filterBy('flo'))
console.log(filterBy('wor'))

这篇关于如何在JavaScript中过滤JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆