は私が名前で、その後数でバス路線を格納していた中で、次のオブジェクト配列があります。JavaScriptでオブジェクトのプロパティ値を動的に取得するにはどうすればよいですか?
var routearray =[
ruta01 =
{
via01: "Progress",
via02: "Ten",
via03: "S",
via04: "Maria"
},
ruta02 =
{
via01: "Exterior",
via02: "Interior"
},
ruta03 =
{
via01: "University",
via02: "Henry St"
},];
をそして私は、私は、各プロパティの値にアクセスしたいと、次のコードを持っている:
for(i=0;i<routearray.length;i++) //iterates through the array's objects
{
var props = Object.keys(routearray[i]); //array that stores the object properties
for(j=0;j<props.length;j++) //iterates through specific object properties
{
console.log(props[j]); //shows the property names
var propertystring = String(props[j]); //transforms the property name into string
console.log(routearray[i].propertystring]; //should access the property value
}
}
コードの最後の行が実行されると、コンソールに8個の「未定義」結果が表示されます。私のようなものに変更した場合:
console.log(routearray[i].via01];
それだけで正常に動作しますが、私は、文字列が正しく動作するようになっている場合、それは値にアクセスしていない理由はわかりません。 私は何が間違っていますか?より良い方法がありますか?
配列要素のプロパティ名を文字列に変換する必要はありません。彼らはすでに弦です。そして、あなたは '[] '演算子を探しています:プロパティ名を含む変数の名前を角括弧に入れます。それはまったく同じことです。 – Pointy
私はそれについて考えましたが、時には複雑な方法を考える傾向があります。ありがとうございました。 –