0
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.

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

4 Comments

React is complaining and the amount is not showing: Warning: Each child in an array or iterator should have a unique "key" prop
@Sylar Did you look at the fiddle I posted? It's working as intended.
Ok. Yes I have seen your typo! You have { item.amount } when it should have been { rowItem.amount }.
nice catch. go team.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.