2015-10-14 19 views
0

我給出了一個字符串'hits.hits'和一個叫做responses的json對象。這個對象包含我想要基於給定的字符串路徑的數據。字符串路徑根據服務返回的數據而變化。用點轉換字符串以訪問javascript中的嵌套對象的指令

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

我怎麼能轉換成字符串參考說明,以便我可以打電話:

var extracted_data = responses.hits.hits;?注意 - 人們將其標記爲立即重複,但這確實是我需要引用該對象的方式。我必須使用這種格式來引用對象。

+0

這不是重複。有一個原因,我可以只用這個調用:'response.hits.hits'。使用此屬性引用方式調用對象! –

+0

也看看http://stackoverflow.com/a/14397052/1048572 – Bergi

回答

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": "[email protected]", 
 
     "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; 
 
    }; 
 
} 
 

 
/***************************************************************************/

+0

嘿,你能詳細說明這是如何工作的嗎? '.split('。')。reduce(function(t,v){return t [v];},responses);'我是javascript新手,不確定reduce是如何工作的。 –

+0

爲了更多地瞭解'reduce',我認爲最好的方法是直接從[mdn]中讀取(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/陣列/減少)如果您需要進一步的解釋,我可以提供他們 – Anonymous0day

+0

這將適用於所有類型的路徑?例如''aggs.nested.container「'或者只有2個級別? –