简体   繁体   English

遍历对象键并将标签添加到值

[英]Loop through object keys and add tags to values

I am trying to render an HTML page from my database using JavaScript and JSON data. 我正在尝试使用JavaScript和JSON数据从数据库中呈现HTML页面。 However, some of the data should be rendered as images while others should be rendered as links. 但是,某些数据应呈现为图像,而其他数据应呈现为链接。 How can I change or add HTML tags? 如何更改或添加HTML标签?

In the database I store the content without any HTML attributes: 我在数据库中存储的内容没有任何HTML属性:

{
  "projects" : {
    "one" : {
      "a" : "E-Network",
      "b" : "/images/projects/unfccc/logo.gif",
      "c" : "/unfccc",
      "d" : "The E-Network"
    },
    "two" : {
      "a" : "User Experience Design",
      "b" : "/images/projects/rex/logo.gif",
      "c" : "/rex",
      "d" : "Rejseplanen Experience"
    }
  }
}

Using React I then pass down an Object with key value pairs to a message component. 然后使用React我将带有键值对的Object传递给消息组件。 Then I render the contents of project.one inside individual tags using Object.keys in a callback method: 然后,我在回调方法中使用Object.keys在单个标签内呈现project.one的内容:

class Message extends React.Component {
   render(){

     function mapObject(object, callback) {
      return Object.keys(object).map(function (key) {
        return callback(key, object[key]);
      });
    }

    return (
      <div>
       {mapObject (this.props.data.one, function(key, value) {
         return <h1 key={key}>{value}</h1>
       })}
      </div>
      )
   }
}
export default Message;

which outputs: 输出:

But how can I control what tag each key value pair is rendered with? 但是,如何控制每个键值对使用的标记? The only solution I see is nesting four Object.keys inside each other and flattening the database structure, but I don't think this is a very good solution, can you tell me a better way to render my data inside HTML tags? 我看到的唯一解决方案是彼此嵌套四个Object.key并展平数据库结构,但是我认为这不是一个很好的解决方案,您能告诉我一种更好的方法来在HTML标签中呈现数据吗?

You are always returning a <div><h1></div> . 您总是返回<div><h1></div> If you detect an image or link use the appropriate tag image or a href 如果您检测到图像或链接,请使用适当的标签imagea href

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM