Diego Fortes
Diego Fortes

Reputation: 9790

Finding all keys with specific name within deeply nested JSON

Overview:

I have a huge JSON object that goes up to 40 levels deep. I need to find all keys that are exactly "videoRenderer". Here is an example of this object.

Issue:

Because of its complexity I can not track down where "videoRenderer" will be displayed at. Therefore I can't just go by "videos.data.videoRenderer". I tried looping it with map but it seems to take a toll on performance.

Goal

The end goal is to have a function like getKeys('videoRenderer') and it will return an array of objects with all the "videoRenderer"s found.

Like this: [{"videoRenderer":{"a":1}},{"videoRenderer":{"b":2}}].

Kindly point me towards a direction to achieve this, I've been stuck on this for a few days now.

Thank you very much!

Upvotes: 2

Views: 2183

Answers (2)

StackSlave
StackSlave

Reputation: 10627

Although the console is slow on Stack Overflow, I got this to work:

//<![CDATA[
/* js/external.js */
let get, post, doc, html, bod, nav, M, I, mobile, S, Q, aC, rC, tC, dig; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('GET', url);
  x.onload = ()=>{
    if(success)success.call(c, JSON.parse(x.responseText));
  }
  x.send();
}
post = function(url, send, success, context){
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('POST', url);
  x.onload = ()=>{
    if(success)success.call(c, JSON.parse(x.responseText));
  }
  if(typeof send === 'object' && send && !(send instanceof Array)){
    if(send instanceof FormData){
      x.send(send);
    }
    else{
      const fd = new FormData;
      for(let k in send){
        fd.append(k, JSON.stringify(send[k]));
      }
      x.send(fd);
    }
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return x;
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
  var w = within || doc;
  return w.querySelector(selector);
}
Q = (selector, within)=>{
  var w = within || doc;
  return w.querySelectorAll(selector);
}
aC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.add(...a);
  return aC;
}
rC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.remove(...a);
  return rC;
}
tC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.toggle(...a);
  return tC;
}
dig = function(obj, func){
  let v;
  if(obj instanceof Array){
    for(let i=0,l=obj.length; i<l; i++){
      v = obj[i]; func(v, i, obj);
      if(typeof v === 'object')dig(v, func);
    }
  }
  else{
    for(let i in obj){
      v = obj[i]; func(v, i, obj);
      if(typeof v === 'object')dig(v, func);
    }
  }
}
// here's where the magic happens
get('https://gist.githubusercontent.com/dpw1/9cecc864dbf80ea66b1698b9c588495f/raw/99e8a210cb4daff5ea013b13c4632c823dbe1f17/ComplexJSON.json', res=>{
  const a = [];
  dig(res, (v, i, o)=>{
    if(i === 'videoRenderer')a.push(v);
  });
  //console.log(a);
});
}); // end load
//]]>

Upvotes: 0

Wyck
Wyck

Reputation: 11740

I might go about it like this:

function allNodes(obj, key, array) {
  array = array || [];
  if ('object' === typeof obj) {
    for (let k in obj) {
      if (k === key) {
        array.push(obj[k]);
      } else {
        allNodes(obj[k], key, array);
      }
    }
  }
  return array;
}

results = allNodes(data, 'videoRenderer');

The for (let k in obj) will iterate over both object properties and array indices alike, both of which will show up as type object. Then recursively ask it to push matching properties into a result array. The example assumes your deeply nested JSON object is called data.

Upvotes: 4

Related Questions