2016-10-10 97 views
0

說我有一個對象獲取json值作爲字符串?

var BOB = { 
"name": "bob", 
"height": 185 
}; 

而且我還有一個目標,從它

var PROPS = { 
"bob": { 
    "height": BOB.height 
}; 

引用值所以現在PROPS.bob.height將等於185。如果我字符串化的對象,我得到

{"bob": {"height": 185}} 

我能計算出的什麼評價返回值185字符串值。例如從代碼中計算源代碼...:

var s = findOutTheSourceCode(PROPS); 

// s would be 
/* 
{ 
"bob": { 
    "height": BOB.height 
} 
*/ 
+1

不,你不能! – adeneo

+1

你能解釋你想達到什麼嗎? – Rajesh

+0

您可以遍歷所有對象屬性以查找路徑。但它只適用於價值唯一的情況下 – k102

回答

0

一般來說,沒有。無論如何,這些信息都不會被存儲。


如果代碼是一個功能你必須是功能您使用支持該非標準功能,那麼一個JS引擎的引用的一部分,您可以撥打thatfunction.toString(),然後嘗試使用(例如)模式匹配找到相關的代碼位。

0

這是一個真的很差想法從設計角度。

無論如何,回答你的問題,簡短的回答是「不,你不能」。

但有一個醜陋回答說是,在依靠使用EVAL這是一個更壞主意的成本。例如:

var BOB = { 
"name": "bob", 
"height": 185 
}; 

var PROPS_src = '{\n' 
    + ' "bob": {\n' 
    + ' "height": BOB.height\n' 
    + ' }' 
    + '}'; 

eval('var PROPS = '+PROPS_src); 

console.log("PROPS_SRC:__________________"); 
console.log(PROPS_src); 
console.log("PROPS:______________________"); 
console.log(PROPS); 

// Output: 
// PROPS_SRC:__________________ 
// { 
// "bob": { 
//  "height": BOB.height 
// }} 
// PROPS:______________________ 
// { bob: { height: 185 } } 

但是,正如我所說,這一切是非常糟糕的主意。我幾乎不建議你重新設計你的數據結構(和需要的代碼),以一種可以追蹤數據源的方式。

對於(快速和骯髒的)例子:

var people = { 
    bob: { 
    "name": "bob", 
    "height": 185 
    } 
}; 

var props = { 
    "bob": { 
    "someConstant": "Hello World", 
    "_height": "height", 
    } 
}; 

function getProps(who){ 
    var out = {}; 
    Object.keys(props[who]).map(function(k){ 
     if (k.substring(0,1) == "_") { 
      out[k.substring(1)] = people[who][props[who][k]]; 
     } else { 
      out[k] = props[who][k]; 
     }; 
    }); 
    return out; 
}; 

console.log("Raw:", props['bob']); 
console.log("Calculated:", getProps('bob')); 

// Output: 
// Raw: { someConstant: 'Hello World', _height: 'height' } 
// Calculated: { someConstant: 'Hello World', height: 185 }