如何显示群组讯息

时间:2019-04-23 09:32:09

标签: javascript reactjs

请帮助我,我是新来的人。我正在从嵌套对象渲染值。每个对象都有标题和消息属性。标题可以相同。我想在标题下显示消息。如果标题与previos对象中的标题相同,则不显示它,仅显示一次。但就我而言,它显示在每条消息之后。

我的对象

arrayOfMessages=[
  {
    title: 'cars',
    message: 'toyota'
  },
  {
    title: 'cars',
    message: 'ford'
  },
  {
    title: 'cars',
    message: 'bmw'
  },
  {
    title: 'bikes',
    message: 'suzuki'
  },
  {
    title: 'bikes',
    message: 'bmw'
  },
]

预期输出:

   title
     message
     message
     message

   title2
     message
     message

就我而言:

   title
     message
   title
     message
   title
     message

   title2
     message
   title2
     message

<div>
          {arrayOfMessages.map((item, idx) => {
            const {
              message,
              title
            } = item
            return (
              <div key={idx} className="message-content">
                <p>{title}</p>
                <p>{message}</p>
              </div>
            )
          })}
        </div>

5 个答案:

答案 0 :(得分:0)

一种方法是通过arrayOfMessages字段将title的项目分组,以通过使用本机.reduce()方法获得所需的呈现结果:

const arrayOfMessages=[
  {
    title: 'cars',
    message: 'toyota'
  },
  {
    title: 'cars',
    message: 'ford'
  },
  {
    title: 'cars',
    message: 'bmw'
  },
  {
    title: 'bikes',
    message: 'suzuki'
  },
  {
    title: 'bikes',
    message: 'bmw'
  },
];

/* Use reduce() to group items of arrayOfMessages by title */
const groupedMessages = arrayOfMessages.reduce((groups, item) => {
  
  /* Find group for the title of current item */
  const group = groups.find(group => group.title === item.title);
  
  /* If matching group found, add message of item to it's messages array */
  if(group) {
    group.messages.push(item.message);
  }
  /* Otherwise, add a new group for this title */
  else {
    groups.push({ title : item.title, messages : [] });
  }

  return groups;
  
}, [])

console.log(groupedMessages);

使用上面的代码,您可以修改render()方法以为每个商品类别一次渲染title

<div>
    { groupedMessages.map((group, idx0) => (<div key={idx0} className="message-content">
        <h2>{ group.title }</h2>
        { group.messages.map((message, idx1) => (<p key={idx1}>{message}</p>)) }        
        </div>))
    }
</div>

希望有帮助!

答案 1 :(得分:0)

您的对象结构不好,应该是这样的:

arrayOfMessages=[
  {
    title:"cars",
    description:["toyota","ford","bmw"]
  },
  {
    title:"bike",
    description:["suzuki","bmw"]
  }
]

然后您可以像这样实现代码:

{
  arrayOfMessages.map((message, idx) => {
    const { description, title } = message
    return (
      <div key={idx} className="message-content">
        <p>{title}</p>
        {description.map((desc, index) => (
          <p key={index}>desc</p>
        ))}
      </div>
    )
  })
}

答案 2 :(得分:0)

您应该首先整理数据。

...
let renderMessages = {}
arrayOfMessages.forEach(message => {
  if (!renderMessages[message.title]) {
    renderMessages[message.title] = {
      title: message.title,
      messages: [message.message]
    }
  } else {
    renderMessages[message.title].messages.push(message.message)
  }
})

return (
  <div>
    {Object.keys(renderMessages).map(key => {
      let msg = renderMessages[key]
      return <div key={key} className="message-content">
        <p>{msg.title}</p>
        {msg.messages.map(content => <p key={content}>{content}</p>)} 
      </div>
    })}
  </div>
)

答案 3 :(得分:0)

您可以使用reduce根据title对消息进行分组。然后遍历合并对象的entries以获取所需的格式

const arrayOfMessages=[{title:'cars',message:'toyota'},{title:'cars',message:'ford'},{title:'cars',message:'bmw'},{title:'bikes',message:'suzuki'},{title:'bikes',message:'bmw'},]

const grouped = arrayOfMessages.reduce((acc, { title, message }) => {
  acc[title] = acc[title] || [];
  acc[title].push(message);
  return acc;
}, {})

console.log(grouped)

这是现场演示:

class Sample extends React.Component {
  render() {
    const arrayOfMessages = [{ title: 'cars', message: 'toyota' }, { title: 'cars', message: 'ford' }, { title: 'cars', message: 'bmw' }, { title: 'bikes', message: 'suzuki' }, { title: 'bikes', message: 'bmw' },]

    const grouped = arrayOfMessages.reduce((acc, { title, message }) => {
      acc[title] = acc[title] || [];
      acc[title].push(message);
      return acc;
    }, {})

    return (
      <div>
        {
          Object.entries(grouped).map(([title, messages], i1) => (
            <div key={i1}>
              <h1>{title}</h1>
              { messages.map((message, i2) => (<p key={i2}>{message}</p>)) }
            </div>)
          )
        }
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Sample />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

答案 4 :(得分:-1)

尝试

 render(){
   //title watcher
   let watcher = {};
   return   <div>
          {arrayOfMessages.map((item, idx) => {
            const {
              message,
              title
            } = item
             if(!watcher[title]){ 
                //update watcher with title
                //if watcher does not contain your title return title and message
                watcher[title]=title;
               return (
              <div key={idx} className="message-content">
                <p>{title}</p>
                <p>{message}</p>
              </div>
               )
             } else {
               //if watcher found with title return your message
                <div key={idx} className="message-content">
                <p>{message}</p>
              </div>
             }



          })}
        </div>

 }