s2k s2k - 2 months ago 14
Javascript Question

How to filter json object in Javascript?

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
}
}


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);


Now how can I filter this
json
object by key name? e.g. If the filter was "ange", the filtered object would be:

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


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

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


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

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


Is it possible to achieve this filtering using the
filter
method? Any advice would be appreciated.

Answer

You can create function using reduce() and Object.keys() that will check key names with indexOf() and return 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'))