Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter a 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?

like image 576
B Faley Avatar asked Sep 17 '16 11:09

B Faley


1 Answers

Beside the given solutions, you could use a recursive style to check the keys.

This proposal gives the opportunity to have more nested objects inside and get only the filtered parts.

function filterBy(val) {
    function iter(o, r) {
        return Object.keys(o).reduce(function (b, k) {
            var temp = {};
            if (k.toLowerCase().indexOf(val.toLowerCase()) !== -1) {
                r[k] = o[k];
                return true;
            }
            if (o[k] !== null && typeof o[k] === 'object' && iter(o[k], temp)) {
                r[k] = temp;
                return true;
            }
            return b;
        }, false);
    }

    var result = {};
    iter(obj, result);
    return 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 }, test: { test1: { test2: { world: 42 } } } };

console.log(filterBy('ange'));
console.log(filterBy('flo'));
console.log(filterBy('wor'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 69
Nina Scholz Avatar answered Oct 25 '22 14:10

Nina Scholz