2017-02-18 95 views
1

我構建了一個React應用程序,我有一個非常複雜的JSON文件,我需要在數組中找到並輸出對象的某些值。與對象和數組嵌套的JSON,找到值

我試着去輸出從我的JSON我的所有的人,他們是這個樣子:

people: [ 
    { 
     "id": 1, 
     "email": "[email protected]", 
     "address": [ 
      { 
       "street": "Kulas Light", 
       "type": "house", 
       "attribute": { 
        "sketch": "sketch.jpg", 
        "photo": "photo.jpg" 
       } 
      }, 
      { 
       "street": "Lorem Ipsum", 
       "type": "apartment", 
       "attribute": { 
        "sketch": "sketch.jpg", 
        "photo": "photo.jpg" 
       } 
      } 
     ] 
    } 
] 

我有輸出沒問題的電子郵件,做它像這樣:

var App = React.createClass({ 

getInitialState: function() { 
    return { 
     results: {} 
    } 
}, 
componentDidMount() { 
    fetch(REQUEST_URL) // fetch from API, returns JSON 
    .then(res => res.json()) 
    .then(data => {this.setState(
     { results: data.people} 
     ); 
    }) 
}, 
renderResult : function(key){ 
    return <Result key={key} index={key} details={this.state.results[key]}/> 
}, 
render : function() { 
    return (
     <ul> 
      {Object.keys(this.state.results).map(this.renderResult)} 
     </ul> 
    ) 
} 
}); 

var Result = React.createClass({ 
render : function() { 
    return (
     <li> 
      {this.props.details.email} 

      <img src="{this.props.details.address.type=house.attribute.photo}"/> 
     </li> 

    ) 
} 
}); 

ReactDOM.render(App, document.querySelector('#app')); 

然而,現在我需要輸出「照片」,但只能輸出「類型」:「房子」。我試過這個,但沒有運氣,深知這是離開的。在處理JSON數據方面我很新,而React和Google甚至在幾個小時試圖解決這個問題後都沒有幫助我。

回答

0

The .address property isn't an object but an array of objects so .type is not available directly on .address :

this.state.results.people.address.type 
// .type property doesn't exist on array 

解決方案:

您可以使用Array.prototype.filter上.address,以獲得具有財產type,其值是 「房子」 對象的數組:

var houseAddresses = this.state.results.people.address.filter(function(value){ 
    return value.type === "house"; 
}); 

在這裏,houseAddress將一組數值爲type值爲'house'的對象。

然後,您可以循環訪問陣列以使用for,Array#forEachArray#map創建相關的JSX。下面的示例使用陣列#地圖:

const houseImgTags = houseAddresses.map(function(house, index){ 
    return (
    <img 
     src={house.attribute.photo} 
     key={'house'+index} 
    /> 
); 
}); 

(在這裏加入的情況下,關鍵有一個house對象的多個實例)

+0

啊,我看到你在做什麼,但我真的不能真正把它工作。嘗試編譯代碼時出現錯誤。 此記錄的所有對象: '變種houseAddresses = this.props.details.address;' 這會導致編譯錯誤: '變種houseAddresses = this.props.details.address.filter((值){ \t \t \t value.type === 「房子」; \t \t});' – dilla

+0

@dilla:需要時聲明函數傳遞給過濾'function'關鍵字:'this.state.results.people.address.filter (function(value){ return value.type ===「house」; });' – Pineda

+0

啊,修好了,很酷,謝謝你r幫助男人!儘管我沒有完全在那裏,但無法設法在我的組件中實現它,它呈現所有信息,例如電子郵件和街道。如果你有時間並且想要,id只是想問你是否可以私下檢查我的代碼?這是一個約70行。 – dilla

-1

你可以簡單地寫。
<img src={this.states.results.address.type==="house"?house.attribute.photo : otherwise_photo}/>
基本上這會比較address.type是不是house,然後返回相應的結果。

+0

'this.states.results.address'沒有'type'屬性,**它是一個包含對象的數組,有'type'屬性** – Pineda