遍历 JavaScript 对象但保留键值
Loop through JavaScript Object but keep key with value
var data = {
2016-09-24: {
0: {amount: 200, id: 2},
1: {...}
},
2016-09-25: {
0: {amount: 500, id: 8},
1: {...}
}
}
我想在如下视图中表示上述数据:
"**" 将是 div 和 card
class:
*****************************************
* <h2>2016-09-24</h2> *
* *
* <li>amount: 200</li> *
* <li>amount: 40</li> *
* *
*****************************************
*****************************************
* <h2>2016-09-25</h2> *
* *
* <li>amount: 500</li> *
* <li>amount: 90</li> *
* *
*****************************************
我还没有达到布局但卡在了循环中。我正在使用 React es6:
dailySales(){
Object.keys(data).forEach(function(key) {
var dates = key;
var val = data[key];
let sales = val.map(function(s, i) {
//console.log(s.amount);
});
});
}
上面注释掉了console.log
会return全部amount
。如何用日期(键)分割每个值?本题类似to this one.
莱昂纳多·迪卡普里奥在 "Inception"、"we need to go deeper"
中的名言
你非常接近并且在正确的轨道上。您需要再次遍历嵌套对象,您将得到您要查找的内容:
Object.keys( data ).map( function( date, i ) {
// here you have the date
return (
<div key={ i }>
<h1>{ date }</h1>
{ Object.keys( data[ date ] ).map( function( item, j ) {
// and here you have the item by its key
var rowItem = data[date][item];
return (
<p key={ rowItem.id }>Amount: { rowItem.amount }</p>
);
})}
</div>
);
});
var data = {
2016-09-24: {
0: {amount: 200, id: 2},
1: {...}
},
2016-09-25: {
0: {amount: 500, id: 8},
1: {...}
}
}
我想在如下视图中表示上述数据:
"**" 将是 div 和 card
class:
*****************************************
* <h2>2016-09-24</h2> *
* *
* <li>amount: 200</li> *
* <li>amount: 40</li> *
* *
*****************************************
*****************************************
* <h2>2016-09-25</h2> *
* *
* <li>amount: 500</li> *
* <li>amount: 90</li> *
* *
*****************************************
我还没有达到布局但卡在了循环中。我正在使用 React es6:
dailySales(){
Object.keys(data).forEach(function(key) {
var dates = key;
var val = data[key];
let sales = val.map(function(s, i) {
//console.log(s.amount);
});
});
}
上面注释掉了console.log
会return全部amount
。如何用日期(键)分割每个值?本题类似to this one.
莱昂纳多·迪卡普里奥在 "Inception"、"we need to go deeper"
中的名言你非常接近并且在正确的轨道上。您需要再次遍历嵌套对象,您将得到您要查找的内容:
Object.keys( data ).map( function( date, i ) {
// here you have the date
return (
<div key={ i }>
<h1>{ date }</h1>
{ Object.keys( data[ date ] ).map( function( item, j ) {
// and here you have the item by its key
var rowItem = data[date][item];
return (
<p key={ rowItem.id }>Amount: { rowItem.amount }</p>
);
})}
</div>
);
});