0

I'm given a string 'hits.hits' and a json object called responses. This object contains the data I want based on the string path given. The string path varies based on the data the service returns.

{
    "hits": {
        "hits": {
            "col": "data",
            "col2": "data",
            "col3": "data"
        }
    }
}

How can I convert the string into reference instructions so that I can call:

var extracted_data = responses.hits.hits;? Note - people marked this as a duplicate immediately, but this is EXACTLY how I need to refer to the object. I have to use this format to reference the object.

Horse Voice
  • 8,138
  • 15
  • 69
  • 120
  • this is not a duplicate. There is a reason I can ONLY invoke using this: `response.hits.hits`. Calling on the object using this property referencing way! – Horse Voice Oct 14 '15 at 15:02
  • Also have a look at http://stackoverflow.com/a/14397052/1048572 – Bergi Oct 14 '15 at 15:05

1 Answers1

1

var log = function(val){
  document.write('<pre>' + JSON.stringify(val,null , ' ') + '</pre>');
};
var responses = {
        "hits": {
            "hits": {
                "col": "data",
                "col2": "data",
                "col3": "data"
            }
        }
    }
        
    var extracted_data = responses.hits.hits;
    log(extracted_data);

    var StringToFind = 'hits.hits';
    extracted_data = StringToFind.split('.').reduce(function( t , v ){ return t[v];} , responses);
    
    log(extracted_data);

/**
*
* More complete test case :
*/

// we create a function 
// to extract the data 
// from src 
// according a path
// 

var extractData = function( path , src , splitter){
  var _splitChar = splitter || '.'; 
  
  // we transform the string in array 
  // splitted by the 'splitter'
  var arr = path.split( _splitChar ); 
  
  return arr.reduce(function( transfomed , value ){ 
    return transfomed[value];
  } , src);
  
};

// let try it :
var objectSource = {
   "tags": [
      "anim",
      "tempor",
      "enim",
      "veniam",
      "duis",
      "duis",
      "et"
    ],
    "person" : {
      "isActive": true,
      "payment" : {
         "balance": "$1,945.05",
       },
       "profil" : {
         "picture": "http://placehold.it/32x32",
         "elements" : [
           { "id" : "square" } ,
           { "id" : "circle" } ,
           { "id" : "triangle" } ,
         ]
       },
       "physic" : {
         "age": 24,
         "eyeColor": "green",
         "gender": "female",
      
       },
      "name": "Pauline Madden",
      "company": {
        "name" : "VALPREAL",
      },
      "email": "paulinemadden@valpreal.com",
      "phone": "+1 (888) 515-2346",
      "address": "939 Gerald Court, Nash, Utah, 7374",
     },
};
           
var dataToFind = 'person.name';
log( extractData( dataToFind , objectSource ));

dataToFind = 'person.company.name';
log( extractData( dataToFind , objectSource ));

dataToFind = 'person.profil.elements.2.id';
log( extractData( dataToFind , objectSource ));

dataToFind = 'tags.2';
log( extractData( dataToFind , objectSource ));
           
 /* Try with another splitter charachter */
           
var dataToFind = 'person/name';
log( extractData( dataToFind , objectSource , "/"));
log( extractData( 'person/address' , objectSource , "/"));
log( extractData( 'person/payment/balance' , objectSource , "/"));
log( extractData( 'person.payment.balance' , objectSource ));
           
/******************************************************************

Polyfill

Array.prototype.reduce was added to the ECMA-262 standard in the 5th edition; 
as such it may not be present in all implementations of the standard. 
You can work around this by inserting the following code 
at the beginning of your scripts, allowing use of reduce 
in implementations which do not natively support it.

*******************************************************************/
           
// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
if (!Array.prototype.reduce) {
  Array.prototype.reduce = function(callback /*, initialValue*/) {
    'use strict';
    if (this == null) {
      throw new TypeError('Array.prototype.reduce called on null or undefined');
    }
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }
    var t = Object(this), len = t.length >>> 0, k = 0, value;
    if (arguments.length == 2) {
      value = arguments[1];
    } else {
      while (k < len && !(k in t)) {
        k++; 
      }
      if (k >= len) {
        throw new TypeError('Reduce of empty array with no initial value');
      }
      value = t[k++];
    }
    for (; k < len; k++) {
      if (k in t) {
        value = callback(value, t[k], k, t);
      }
    }
    return value;
  };
}

/***************************************************************************/
Anonymous0day
  • 3,012
  • 1
  • 14
  • 16
  • Hey could you please elaborate on how this works? `.split('.').reduce(function( t , v ){ return t[v];} , responses);` I'm new to javascript and not sure how the reduce works. – Horse Voice Oct 14 '15 at 15:50
  • the best way for you to learn more about `reduce`, i think, is to read directly [from mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) If you need further explanation, I could provide them – Anonymous0day Oct 14 '15 at 16:20
  • will this work for for all types of paths? for example `"aggs.nested.container"` or only 2 levels? – Horse Voice Oct 14 '15 at 17:11
  • Yes it will i've updated my answer to reflect this ! just try and tell me ! – Anonymous0day Oct 14 '15 at 17:42
  • thanks. BTW, this didn't work in IE. But mozilla it works fine. – Horse Voice Oct 14 '15 at 21:21
  • Which version of IE ? i've updated my code at the end ! i've added a [polyfill](https://en.wikipedia.org/wiki/Polyfill) you can use safely, it come from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce), with older browser that do not support Array.reduce – Anonymous0day Oct 14 '15 at 21:43
  • Thank you for your help. – Horse Voice Oct 15 '15 at 14:58