D
D
Dima2018-03-05 13:56:48
JSON
Dima, 2018-03-05 13:56:48

How to iterate json normally?

a lot of text, but for example
, here is my react code.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';


import text from './product.json';
import cont from './cont.json';

  
class App extends Component {
    
    	render() {



        return (
     
      <div className='shopping-list'>
        <ul className='list-tem'>                                                   
                                             
                                             
          {text.map( function (item, index) {
            return (<li key={index}>{item.id}   {item.title} <img src={item.image} alt=""/>   </li>    );} )
          }
                                
        </ul>
      </div>
    )
        
        
 
  };

}
export default App;

here is an example product.json file
[{
    "id": 0,
    "image": "https://picsum.photos/200/220",
    "price": 263.79,
    "title": "Occaecat"
}, {
    "id": 1,
    "image": "https://picsum.photos/200/221",
    "price": 424.76,
    "title": "Consectetur"
} ]

everything outputs correctly.
here the data is peer-to-peer.
but with this json
{
  "continents": [
    {
      "code": "AF",
      "name": "Africa"
    },
    {
      "code": "AN",
      "name": "Antarctica"
    },
    {
      "code": "AS",
      "name": "Asia"
    },
    {
      "code": "EU",
      "name": "Europe"
    },
    {
      "code": "NA",
      "name": "North America"
    },
    {
      "code": "OC",
      "name": "Oceania"
    },
    {
      "code": "SA",
      "name": "South America"
    },
    {
      "code": "??",
      "name": null
    }
  ]
}

this code is not working. how to output data from such json?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-03-05
Dolgoter @DDolgy

Before you undertake such things to implement, you should study the basics of JavaScript well.
In the first case, you have an array in json , in the second, an object containing an array.
You can iterate over the elements in the second case like this:

{cont.continents.map(el => (
  <li key={el.code}>{el.name}</li>
))}

I highly recommend that you put React aside for now and spend a couple of days learning the basics of JavaScript , as well as the ES6 syntax , JSX , and experimental language features used in React .

R
Roman Aleksandrovich, 2018-03-05
@RomReed

try this

{Object.keys(text).map( 
 (item, index) =>{
            return (<li key={index}>{text[item].id}   {text[item].title} <img src={text[item].image} alt=""/>   </li>    );} )
          }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question