dolor3sh4ze
dolor3sh4ze

Reputation: 1165

Search through a deep JSON file

I would like to find a JSON object by looking for a special key from the inside. For example in the following case:

{
  "1": {
    "name": "usa",
    "position": 8,
    "code": 1,
    "other": false,
    "new": false,
    "enabled": true,
    "services": {
      "service_vkcom": {
        "count": 6039,
        "popular": false,
        "code": 1,
        "id": 1,
        "service": "Вконтакте",
        "slug": "vkcom"
      },
      "service_3223": {
        "count": 4053,
        "popular": false,
        "code": 1,
        "id": 2,
        "service": "Facebook",
        "slug": 3223
      }
}

Looking up the word "usa," I'd like the whole "1" thing to come back to me.

Upvotes: 1

Views: 469

Answers (2)

vincent
vincent

Reputation: 2181

Here is an answer that uses object-scan

// const objectScan = require('object-scan');

const data = {"1":{"name":"usa","position":8,"code":1,"other":false,"new":false,"enabled":true,"services":{"service_vkcom":{"count":6039,"popular":false,"code":1,"id":1,"service":"Вконтакте","slug":"vkcom"},"service_3223":{"count":4053,"popular":false,"code":1,"id":2,"service":"Facebook","slug":3223}}}};

const find = (obj, name) => objectScan(['**.name'], {
  abort: true,
  rtn: 'parent',
  filterFn: ({ value }) => value === name
})(obj);

console.log(find(data, 'usa'));
// => { name: 'usa', position: 8, code: 1, other: false, new: false, enabled: true, services: { service_vkcom: { count: 6039, popular: false, code: 1, id: 1, service: 'Вконтакте', slug: 'vkcom' }, service_3223: { count: 4053, popular: false, code: 1, id: 2, service: 'Facebook', slug: 3223 } } }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>

Disclaimer: I'm the author of object-scan

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28424

You can search recursively for the value and return the object it's in:

let obj = {
  "1": {
    "name": "usa",
    "position": 8,
    "code": 1,
    "other": false,
    "new": false,
    "enabled": true,
    "services": {
      "service_vkcom": {
        "count": 6039,
        "popular": false,
        "code": 1,
        "id": 1,
        "service": "Вконтакте",
        "slug": "vkcom"
      },
      "service_3223": {
        "count": 4053,
        "popular": false,
        "code": 1,
        "id": 2,
        "service": "Facebook",
        "slug": 3223
      }
    }
  }
};

function getParent(obj, val) {
    let res = []; 
    for(let p in obj)
        if (typeof(obj[p]) == 'object')
            res = res.concat(getParent(obj[p], val));
        else if (obj[p] == val) 
            res.push(obj);
    return res;
}

console.log(getParent(obj, "usa"));
console.log(getParent(obj, 6039));
console.log(getParent(obj, "Facebook"));

Upvotes: 2

Related Questions