最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - return html for every key in object - Stack Overflow

programmeradmin1浏览0评论

I do apologize in advance I'm a JS/ReactJS newbie and I have had trouble phrasing the question, so if this is already answered somewhere I am sorry.

I have an object like this: Object {Joy: 0.719115, Extraversion: 0.59527, Agreeableness: 0.650457}

I'd like to be able to return html for all of the keys in the object. As of right now it only returns the html for the first key (obviously, as return breaks the loop, if I'm not mistaken). How do I achieve rendering of html of all the keys from the object?

import React from 'react'

export const MessageSentiment = (props) => {
  var sentiment = JSON.parse(props.sentiment)
  console.log(sentiment)
    for(var key in sentiment ) {
      console.log(key, sentiment[key])
      return (<h1>{key}: {sentiment[key]*100}</h1>)
    }
}

These are the output and required output

Output:
<h1>Joy: 71.9115</h1>


Expected output:
<h1>Joy: 71.9115</h1>
<h1>Extraversion: 59.527</h1>
<h1>Agreeableness: 65.0456</h1>

Not sure if this has anything to do with it, but I get a warning in the console:

../src/ponents/messages/MessageSentiment.js
  6:5  warning  The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype  guard-for-in

✖ 1 problem (0 errors, 1 warning)

printWarnings @ webpackHotDevClient.js:196
handleWarnings @ webpackHotDevClient.js:209
connection.onmessage @ webpackHotDevClient.js:255
EventTarget.dispatchEvent @ eventtarget.js:49
(anonymous) @ main.js:274
SockJS._transportMessage @ main.js:272
EventEmitter.emit @ emitter.js:44
WebSocketTransport.ws.onmessage @ websocket.js:35

I do apologize in advance I'm a JS/ReactJS newbie and I have had trouble phrasing the question, so if this is already answered somewhere I am sorry.

I have an object like this: Object {Joy: 0.719115, Extraversion: 0.59527, Agreeableness: 0.650457}

I'd like to be able to return html for all of the keys in the object. As of right now it only returns the html for the first key (obviously, as return breaks the loop, if I'm not mistaken). How do I achieve rendering of html of all the keys from the object?

import React from 'react'

export const MessageSentiment = (props) => {
  var sentiment = JSON.parse(props.sentiment)
  console.log(sentiment)
    for(var key in sentiment ) {
      console.log(key, sentiment[key])
      return (<h1>{key}: {sentiment[key]*100}</h1>)
    }
}

These are the output and required output

Output:
<h1>Joy: 71.9115</h1>


Expected output:
<h1>Joy: 71.9115</h1>
<h1>Extraversion: 59.527</h1>
<h1>Agreeableness: 65.0456</h1>

Not sure if this has anything to do with it, but I get a warning in the console:

../src/ponents/messages/MessageSentiment.js
  6:5  warning  The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype  guard-for-in

✖ 1 problem (0 errors, 1 warning)

printWarnings @ webpackHotDevClient.js:196
handleWarnings @ webpackHotDevClient.js:209
connection.onmessage @ webpackHotDevClient.js:255
EventTarget.dispatchEvent @ eventtarget.js:49
(anonymous) @ main.js:274
SockJS._transportMessage @ main.js:272
EventEmitter.emit @ emitter.js:44
WebSocketTransport.ws.onmessage @ websocket.js:35
Share Improve this question edited Mar 4, 2017 at 15:02 Borko Kovacev asked Mar 4, 2017 at 14:48 Borko KovacevBorko Kovacev 1,0202 gold badges14 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Two things here.

  1. You need to always return one single element, in this case a div. Inside of this element you can have whatever you want, but it has to be a single parent ponent.

  2. You will use map to iterate an array and get a new array. In this case the new array will contain the <h1/> elements.

```

export const MessageSentiment = (props) => {
  const sentiments = JSON.parse(props.sentiment);
  const keys = Object.keys(sentiments);

  return (
    <div>
     { keys.map(key => (<h1 key={key}>{key}: {sentiments[key]*100}</h1>)) }
    </div>
  );    
}

```

Regards

A React ponent can't return multiple React elements. You should wrap them inside <div> or any other container element.

export const MessageSentiment = (props) => {
  var sentiment = JSON.parse(props.sentiment)
  return (
    <div>
      {
        Object.keys(sentiment).map(key => (
          <h1 key={key}>{key}: {sentiment[key]*100}</h1>
        ))
      }
    </div>
  )
}

And remember: keys should be given to the elements inside the array to give the elements a stable identity.

you need to collect all the HTML in the array and return it. you can do 2 way

  1. using map - map return new array without modifying existing array

.

export const MessageSentiment = (props) => {
              var sentiment = JSON.parse(props.sentiment)
              return (
                     <div>
                      {
                         Object.keys(sentiment).map((key, index) => <h1 key={index}> {key}:{sentiment[key]*100}</h1>)
                      }
                    </div>
                      )
              }
  1. Using array push method

.

 export const MessageSentiment = (props) => {
     var sentiment = JSON.parse(props.sentiment)
     let itemList = [];
     for(var key in sentiment ) {
       itemList.push(<h1>{key}: {sentiment[key]*100}</h1>)
     }
     return (
             <div>{itemList}</div>
           )
     }
发布评论

评论列表(0)

  1. 暂无评论