JSONは関数を処理できないため、JSONオブジェクトのキーフラグでJSON文字列を評価する必要があります。 JSONデータがObjectフォームのときに変更したいと思います。JavaScriptオブジェクトを再帰的にトラバースし、値をキーで置き換えます。
既知のキーパターンに基づいてキーへのフルパスを与えることができる関数/メソッドをオンラインで見つけることができません。
は、このデータを考える:{
"js:bindto": "#chart-1", // note the key here 'js:'
"point": {
"r": 5
},
"data": {
"x": "x",
"xFormat": "%Y",
"columns": [
...
],
"colors": {
"company": "#ed1b34",
"trendline": "#ffffff"
}
},
"legend": {
"show": false
},
"axis": {
"x": {
"padding": {
"left": 0
},
"type": "timeseries",
"tick": {
"format": "%Y",
"outer": false
}
},
"y": {
"tick": {
"outer": false,
"js:format": "d3.format(\"$\")" // note the key here 'js:'
}
}
},
"grid": {
"lines": {
"front": false
},
"y": {
"lines": [...]
}
}
}
フラグがjs:
で始まるキーです。
/js:bindto
と/axis/y/tick/js:format
のようなパスになると、私はjs:format
を調べます。提案に開放されています。
mutateGraphData<T>(data:T):T {
// data here is a parsed JSON string. (an object as shown above)
let jsonKeys = this.findKeysInJSON(JSON.stringify(data), "js:");
// jsonKeys = ["js:bindto","js:format"]
jsonKeys.map((key:string) => {
// find the key in data, then modify the value. (stuck here)
// i need the full path to the key so i can change the data property that has the key in question
});
});
return data;
}
findKeysInJSON<T>(jsonString:string, key:string):Array<T> {
let keys = [];
if (Boolean(~(jsonString.indexOf(`"${key}`)))) {
let regEx = new RegExp(key + "(\\w|\\-)+", "g");
keys = jsonString.match(regEx);
}
return keys;
}
私はいくつかのNPMパッケージの周りされています:
- object searchなしワイルドカード
- dottyがよさそうだが、検索で失敗前後参照:「* .jsの文脈では
:フォーマット "
- https://github.com/capaj/object-resolve-path - キーへのフルパスが必要です。私はそれを前もって知らない。
私は私が完全なパスを返すことができます見てきました
- JavaScript recursive search in JSON object
- Find property by name in a deep object
- DefiantJS(なしNPMモジュール)
- https://gist.github.com/iwek/3924925
何も見てきました私はmodiできるので、問題の鍵私はそのプロパティを変更することができますので、オブジェクト自体に直接作業しないでください。
言語のために 'mutateGraphData(data:T):T'とは何ですか? –
@NinaScholz:TypeScript。 –