2016-05-04 2 views
-2

は私がJavaスクリプトオブジェクトを持っていると私は動的にそれから特定の値にアクセスし、何かにそれを変更しようとしている値ダイナミック深いアクセスが

マイオブジェクト:たとえば場合について

myJson = { 
      "id" : "http://**********", 
      "$schema": "http://json-schema.org/draft-04/schema", 
      "type" : "object", 
      "properties":{ 
      "AddressLine1" :{"type":"string" , "maxLength":62}, 
      "AddressLine2" :{"type":"string" , "maxLength":62}, 
      "city" :{"type":"string" , "maxLength":62}, 
      "state" :{"type":"string" , "maxLength":5} 
     }, 
     "required": ["AddressLine1", "city"] 
     } 

私は、だから私は、私はに基づいて値にアクセスする必要があります変数「パス」に基づいて

path = "$.properties.state.maxLength"; 

動的に与えられた「パス」に基づいて、状態オブジェクトでのmaxLengthにアクセスする必要がありますパスを編集して編集します。

全コード:

var sample = function(){ 


    var myJson = { 
     "id" : "http://application.nw.com/address", 
     "$schema": "http://json-schema.org/draft-04/schema", 
     "type" : "object", 
     "properties":{ 
     "AddressLine1" :{"type":"string" , "maxLength":62}, 
     "AddressLine2" :{"type":"string" , "maxLength":62}, 
     "city" :{"type":"string" , "maxLength":62}, 
     "state" :{"type":"string" , "maxLength":5} 
    }, 
    "required": ["AddressLine1", "city"] 
    } 

    // I get the path from an external source. 
    path = "$.properties.state.maxLength"; 

    path = path.substring('$.'.length); 
    console.log(path);   // log = properties.state.maxLength 
    console.log(myJson.properties.state.maxLength);  // log 5 
    console.log(myJson.path);      // log undefined 


} 

私は初心者のPLSのヘルプと私は本当に愚かな何かをした場合、奨励してみてください。間違い

+6

これはJSONではなく、JavaScriptオブジェクトです。 – Biffen

+3

あなたは 'path = myJson.properties.state.maxLength;'を試してみましたか? –

+0

@FelippeDuarteには正しい答えがあります。 'properties'はそれ自身では存在しないので、最初に適切なオブジェクトを指す必要があります – colecmc

答えて

1

あなたはプロパティにアクセスするために、パスを解析する必要がある場合は

おかげ

は、それを編集すること自由に感じなさい。

pathが可変であるので、myJson.pathは意味がありません。 dotという表記は、プロパティを示します。

変数のコンテンツに基づいてプロパティに動的にアクセスする必要があるため、bracketという表記法を使用する必要があります。あなたがオブジェクトに降りる深さの各レベルは、それ自身のブラケットを必要とします。ブラケット表記法を使用して

console.log(myJson) --> the object 
console.log(myJson["properties"] --> the properties property of the object 
console.log(myJson["properties"]["state"] --> the state property of the properties property 

、あなたはその構成部品にpath変数を解析することができます

var p1 = "properties"; 
var p2 = "states"; 
var p3 = "maxLength"; 
console.log(myJson[p1][p2][p3]); 

Here is a fiddle demo

関連する問題