Picking up parts of a JSON vector

Asked

Viewed 1,640 times

2

I am doubtful about the GET function of my JS (React JS) code, I have the GET function using the Fetch api, it returns the values a certain link.json containing an array. Using this link as an example: http://jsonplaceholder.typicode.com/posts - I want to take the contents of the first 'Id'(1) and put in one part of the code, and also another 'Id' (Example: 5) any of the array to another part of the code.

constructor(props) {
  super(props);
  this.state = {
      data:[]
      }
  }
  componentDidMount(){
        let URL = 'http://jsonplaceholder.typicode.com/posts'

           fetch(URL)
           .then(function(response) {
              let data = response.json()
              return data;
           })
           .then((json) => {
              console.log('mensagens: ', json)
              this.setState({data : json});
           })
           .catch(function(ex) {
              console.log('parsing failed', ex)
           })
  }

UPDATING:

      {
         this.state.data.map(obj => (
           if(obj.displayPortraitLeft == true){
             <div className="box-body">
            <div className="direct-chat-msg undefined">
                      <div className="direct-chat-info clearfix">
                      <span className="direct-chat-name pull-right">{obj.userName}</span>
                      <span className="direct-chat-timestamp pull-left">{obj.time}</span>
                      </div>
               </div>
             </div>
           }else{
               <div className="box-body">
            <div className="direct-chat-msg undefined">
                      <div className="direct-chat-info clearfix">
                      <span className="direct-chat-name pull-right">{obj.userName}</span>
                      <span className="direct-chat-timestamp pull-left">{obj.time}</span>
                      </div>
               </div>
             </div>
         ))
     }

Returns in browser : . /src/chat/Chat.js Syntax error: C:/Users/Henri/Desktop/funcionando/my-app/src/chat/Chat.js: Unexpected token (41:19)

  39 |              {
  40 |                  this.state.data.map(obj => (
> 41 |                    if(obj.displayPortraitLeft == true){
     |                    ^
  42 |                      <div>
  43 |                      <div className="box-body">
  44 | 
  • Hi Henrique. You solved yesterday’s CSS question?

  • I got the position part of each widget in different screen sizes, like: Small screens one below the other, Medias screens, 2 columns and 2 Rows...

  • Okay, if you don’t have it all figured out, just put the rest of the HTML or JSX in there so we can help. I answered that question here, though, see if it makes sense, and that’s what you’re looking for. In the other questions I see that you are using other components, here I gave example with simple html.

  • Henrique, you can simplify your IF already line 41. If the value of obj.displayPortraitLeft is true or false, you can leave it alone if (obj.displayPortraitLeft)

1 answer

2


You can do it like this, using the this.state.data as array that is and iterating with map to generate JSX

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    }
  }
  componentDidMount(){
        let URL = 'https://jsonplaceholder.typicode.com/posts'
           fetch(URL)
           .then(function(response) {
              let data = response.json()
              return data;
           })
           .then((json) => {
              console.log('mensagens: ', json)
              this.setState({data : json});
           })
           .catch(function(ex) {
              console.log('parsing failed', ex)
           })
  }
  render(){
      return (
          <div>
            {
                this.state.data.map(obj => (
                  <div>{obj.id} {obj.title}</div>
                ))
            }
          </div>
      );
  }
}
ReactDOM.render(
  <App/>,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

  • Okay, in that sense I managed to rotate, but if for example I want to take only the third sentence of your comment "3 ea molestias quasi exercitationem repellat qui ipsa sit aut", which syntax used to manipulate the vector JSON?

  • @Henriquehermes where do you have the information that is only id3? is an input? or is it in this.state.filtro: [3, 5] for example?

  • Let’s imagine the following, I have an array in JSON, several inserted elements: [ { "userid": 1 } { "userid": 122 } { "userid": 133 } ] and I wanted to take only"

  • @Henriquehermes in that case you could do arr[1].userId but that’s too specific, I don’t think that’s what you need... In the example above the fetch brings several posts. Where in the code you know that is the 3 What do you want to show? Yeah state? or prop or a <input>?

  • is that I am developing a 'chat', where I already start it with inserted messages, and the JSON that I am picking up these messages, are in Array format, in this JSON I have 2 users, and each user has 2 or 3 messages ready, if I use this code above it takes all the contents passed by the key, in java I would use something similar to arrayJson[2]. message -> Chat image to be developed https://uploaddeimagens.com.br/imagens/capture-png-215

  • @Henriquehermes then and you know the Ids of these messages already pre-inserted?

  • In the JS code, I would put the specific message here: <div classname="direct-chat-text"> VECTOR MESSAGE of the position [x] </div>

  • @Henriquehermes yes, that’s simple, but you know the value of x?

  • I know the values, in the console.log I will be guided by the username. https://uploaddeimagens.com.br/imagens/capture-png--216 ---- Each line of this vector contains a message

  • @Henriquehermes then just want to show the messages that have a certain userName that’s it?

  • More or less that, the meaning is equal to our comments here in stackoverflow, one is below the other, my message corresponds to the position [0] of the vector JSON, and yours to the position [1], the following [2].. [3] etc., I want the codigo js that I am developing, first read only the content of the position [0], and printe in a chat field, below it I want to do the same thing, only with the content of the position [1]

  • @Henriquehermes but in the example I gave does this, prints the [0] to the end of the array. But more than that you want it to print only if it has user == 'Mary' or user == 'John'? I’m a little lost still with what you want to do...

  • 1

    You’re right, I checked the code here and made some changes, it’s working properly.

  • @Henriquehermes great!

  • i can make comparison using the data of the JSON vector? I have a field with "displayPortraitLeft":false -- I can make a comparison in . JS with IF and ELSE? In the sense that if "displayPortraitLeft" is false, use a different CSS than "displayPortraitLeft" is true

  • if({obj.displayPortraitLeft} == false){ Any code that uses a class with right padding } }

  • @Henriquehermes yes. It should be f(obj.displayPortraitLeft == false){ without {}.

  • I put the question, an error that appears in my browser, I did not detect what is wrong

  • @Henriquehermes avoids changing the question. So my answer to the specific subject is meaningless. If you have problems, ask a new question. In that case you have obj => ( and should be obj => { and then } at the end of that callback.

  • Okay, I opened a new question if I wanted to check: https://answall.com/questions/252683/condi%C3%A7%C3%A3o-if-Else-reactjs-json

Show 15 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.