2016-04-12 10 views
-1

他のガイドに従おうとしましたが、動作していないようです。私はこのようになります別のJSONファイル内の最初のオブジェクト(スニペット)を取得したい:JSONの最初のオブジェクトにアクセスできません

{ 
    "employees": [{ 
     "occupation": "cook", 
     "id": [{ 
      "address": { 
       "postal_code": 12342, 
       "city": "detroit" 
       }, 
       "children": "none" 
     ], 
} 
} 
      // and so forth, there are more objects in the employees-array 

私のコードスニペットは、次のようになります。

$.getJSON(url, function(data) { 
    $.each(data.employees, function(i, emp) { 
     if (this.id.length) { 
      console.log(this[0].address.city); 
     } 
    } 

私が最初のオブジェクトの「アドレスにアクセスしたいです" `console.log(this.address [0] .city);とタイプすると、" employees "のすべてのオブジェクトからすべての最初の" city "値が取得されます。

ありがとうございます! each()インサイド

+0

'places'は何ですか? –

+1

あなたは 'id'プロパティを逃しました。 –

+0

申し訳ありませんが、質問をアップロードする際に変数の名前を変更し、特定の変数を忘れました。編集されました。 – Jeramo

答えて

1

私が正しくあなたの問題を理解している場合、および@Velimir Tchatchevskyのコメントに基づいて、私はあなたが何をしたいと思いますが、次のとおりです。

data.employees[0].id[0].address.city 

jsfidle

+0

はい、まさにそれです!皆さんの努力のために大変ありがとうございます! :) – Jeramo

4

thisは、あなたがこれにconsole.log()を改正する必要があるので、employeeオブジェクトを参照します:あなたは、各ブロックでのemp変数を使用していないのはなぜ

$.each(data.employees, function(i, emp) { 
    if (this.id.length) { 
     console.log(this.id[0].address.city); 
    } 
}); 
+0

私もそれを試みましたが、私はまだ "従業員"のすべてのオブジェクトからすべての "都市"値を取得しています。 – Jeramo

+0

[this fiddle](https://jsfiddle.net/5mk61k8c/1/)からわかるように、上記のことは 'id'配列内に複数のオブジェクトがあっても正しく動作します。 –

3

$.each(data.employees, function(i, emp) { 
    if (emp.id.length) { 
     console.log(emp.id[0].address.city); 
    } 
} 
+0

残念ながら、 "this"を "emp"に変更しても違いはありません... – Jeramo

+0

emp.id.lengthの代わりに(emp.id [0])をチェックします(empにアクセスしたい場合は、 id [0]) – Areca

1

最初は、あなたのオブジェクトは、このコードを試してみてください

{ 
    "employees": [{ 
     "occupation": "cook", 
     "id": [{ 
      "address": { 
       "postal_code": 12342, 
       "city": "detroit" 
       }, 
       "children": "none" 
     ], 
} 
} 

です。

$.each(data.employees, function(i, emp) { //each function will able access each employees 
    if (this.id.length) { 
     console.log(this.id[0].address.city); // at each employee get the first element of array id. 
    } 
} 
  1. .each機能はemployees配列外に通過します。
  2. this.id[0]これはidとして識別される配列の最初の要素にアクセスできます。 IDの内部にはアドレスオブジェクトがあります。

      "address": { 
           "postal_code": 12342, 
           "city": "detroit" 
           } 
    
  3. this.id[0].address: - このコードは、あなたのアドレスオブジェクトを提供します。

       { 
           "postal_code": 12342, 
           "city": "detroit" 
           } 
    
  4. this.id[0].address.city: - アドレスオブジェクト内には、コードのこの部分を使用して、今の都市を取得します。ここでは、

    "city": "detroit" 
    

おかげで...あなたの回答を得ただろう。

関連する問題