ReactJs - 在JSON响应中访问嵌套数组

时间:2016-04-03 17:08:19

标签: javascript reactjs

JSON响应:



Bars: [
{
id: "7",
name: "The Trestle Inn",
address: "339 N 11th St",
city: "Philadelphia",
state: "PA",
category: "Dive Bar",
checkIn: [
{
wait: "0.1",
vibe: "0.35",
crowd: "0.5"
}
],
eventname: "0"
},
{
id: "9",
name: "McGillin's Olde Ale House",
address: "1310 Drury Street",
city: "Philadelphia",
state: "PA",
category: "Pub",
checkIn: [
{
wait: "0.1",
vibe: "0.4",
crowd: "0.2"
}
],
eventname: "0"
},




我正在使用ReactJs,并尝试迭代" Bars",提取数据。我可以成功访问第一层响应,例如名称和地址,但我无法处理子数组" checkIn",我想在其中提取' vibe&#39的值;,等等'和#39;



var WebApp = React.createClass({
	componentDidMount: function(){
		this.loadFavoritesData();
	},

	render: function(){
		return(
						<div>
							<Favorites favoritesData={this.state.favoritesData} />
							<Newsfeed />
						</div>
			)
	}
});

var Favorites = React.createClass({
	render: function(){
		//console.log(this.props.favoritesData);

		var favoriteNodes = this.props.favoritesData.map(function(favorite, index){

			var checkInNodes = favorite.checkIn.map(function(data){
				//console.log(data.vibe);
				return {data}
			});

			console.log(checkInNodes.vibe);
			
			return(
						<Favorite
						name={favorite.name}
						address={favorite.address}
						key={index}
						vibe={checkInNodes.vibe}
						/>

				)
		});

		return(
					<div>
							<h2 className="page-header">Favorite Bars</h2>
							{favoriteNodes}
					</div>
			)
	}
});

var Favorite = React.createClass({
	render: function(){
		return(
				<div className="favoriteItem">
					<h4>{this.props.name}</h4>
					<p>{this.props.address}</p>
					<p>Vibe: {this.props.vibe}</p>
				</div>
			)
	}
});
&#13;
&#13;
&#13;

我最初认为我可以在Favorites组件中的第一个map函数中访问它,但是在尝试类似下面的内容时,我得到了favorite.checkIn.vibe的未定义结果,尽管如果我是console.log(favorite.checkIn) )我将返回对象,我再也看不到了

&#13;
&#13;
var Favorites = React.createClass({
	render: function(){
		var favoriteNodes = this.props.favoritesData.map(function(favorite, index){
			console.log(favorite.checkIn.vibe);
			return(
						<Favorite
						name={favorite.name}
						address={favorite.address}
						key={index}
						vibe={favorite.checkIn.vibe}
						/>

				)
		});
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

简答

我想你想这样做:

Bars[0].checkIn[0].wait

上面的代码中似乎缺少第二个索引。

更长的答案

如果checkIn数组中只有一个对象,您可能需要考虑将它们从数组中取出,以便对象看起来像这样:

{
    id: "9",
    name: "McGillin's Olde Ale House",
    address: "1310 Drury Street",
    city: "Philadelphia",
    state: "PA",
    category: "Pub",
    checkInWait: "0.1",
    checkInVibe: "0.4",
    checkInCrowd: "0.2",
    eventname: "0"
}

然后代码会更清晰。如果您无法更改数据,请尝试以下操作:

for (var i = 0; i < Bars.length; i++) {
  // set the variables above the checkIn
  for (var j = 0; j < Bars[i].checkIn.length; j++) {
    // set Bars[i].checkIn[j].wait
    // set Bars[i].checkIn[j].vibe
    // set Bars[i].checkIn[j].crowd
  }
  // set the eventname variable
}