G
G
gsdev992019-02-07 09:38:08
React
gsdev99, 2019-02-07 09:38:08

How to properly work with array indexes in js (first and last)?

Hello. Please tell me how to correctly implement the following logic:
I will give a standard example of data output:
app.js

import React from 'react'
import ReactDOM from 'react-dom'
import AppReact from './app-react'

const data = [
  {
    id: 1,
    title: 'item1',
    round: [
      {id: 1, total: 1000},
      {id: 2, total: 2000}
    ]
  },
  {
    id: 2,
    title: 'item2',
    round: [
      {id: 1, total: 3000},
      {id: 2, total: 4000}
    ]
  },
  {
    id: 3,
    title: 'item3',
    round: [
      {id: 1, total: 5000},
      {id: 2, total: 6000}
    ]
  },
  {
    id: 4,
    title: 'item4',
    round: [
      {id: 1, total: 7000},
      {id: 2, total: 8000}
    ]
  },
  {
    id: 5,
    title: 'item5',
    round: [
      {id: 1, total: 9000},
      {id: 2, total: 10000}
    ]
  },
  {
    id: 6,
    title: 'item6',
    round: [
      {id: 1, total: 11000},
      {id: 2, total: 12000}
    ]
  },
  {
    id: 7,
    title: 'item7',
    round: [
      {id: 1, total: 13000},
      {id: 2, total: 14000}
    ]
  },
  {
    id: 8,
    title: 'item8',
    round: [
      {id: 1, total: 15000},
      {id: 2, total: 16000}
    ]
  }
]

ReactDOM.render(
  <AppReact data={data} />,
  document.getElementById('react-root')
)

app-react.js
import React from 'react'

class AppReact extends React.Component {
  constructor(props) {
    super(props)
    console.log(props.data);
  }

  render() {
    return (
      <div>
        {
          this.props.data.map((item) => {
            console.log('item', item);
            return (
              <div key={item.id}>
                {item.title}
                {item.round.map((r) => {
                  console.log('r', r);
                  return (
                    <div key={r.id}>
                      {r.total}
                    </div>
                  )
                })}
              </div>
            )
          })
        }
      </div>
    )
  }
}

export default AppReact;

Tell me please. How can I infer that the first element has class="first" for example, and the last element has class="second".

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-02-07
@gsdev99

We create an object that will establish correspondences between indices and classes:

const classes = {
  0: 'first',
  [props.data.length - 1]: 'last',
};

And we use it: className={classes[i]}.
https://jsfiddle.net/w79a6q41/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question