我構建了一個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甚至在幾個小時試圖解決這個問題後都沒有幫助我。
啊,我看到你在做什麼,但我真的不能真正把它工作。嘗試編譯代碼時出現錯誤。 此記錄的所有對象: '變種houseAddresses = this.props.details.address;' 這會導致編譯錯誤: '變種houseAddresses = this.props.details.address.filter((值){ \t \t \t value.type === 「房子」; \t \t});' – dilla
@dilla:需要時聲明函數傳遞給過濾'function'關鍵字:'this.state.results.people.address.filter (function(value){ return value.type ===「house」; });' – Pineda
啊,修好了,很酷,謝謝你r幫助男人!儘管我沒有完全在那裏,但無法設法在我的組件中實現它,它呈現所有信息,例如電子郵件和街道。如果你有時間並且想要,id只是想問你是否可以私下檢查我的代碼?這是一個約70行。 – dilla