Search code examples
htmlreactjsobject-literal

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: {...}
  }
}

I want to represent the above data in a view like:

"**" would be a div with a 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>                   *
*                                       *
*****************************************

I have yet to reach the layout but stuck at the loop. Im using 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);
    });
  });
}

The above commented out console.log would return all amount. How to segment each value with the date (key)? This question is similar to this one.


Solution

  • In the wise words of Leonardo DiCaprio in "Inception", "we need to go deeper"

    You're super close and on the right track. You need to loop over the nested objects again and you'll get what you're looking for:

    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>
        );
    
    });
    

    https://jsfiddle.net/64s0yvvz/1/