JS减少收益[对象对象]

时间:2018-10-09 07:01:58

标签: javascript reduce

有对象数组

this.props.comments = [{
id: "b149b076-93b1-4ac7-b913-65a7b1ee9a5b", 
addedBy: "user1", 
addedById: "3dc8e8a0-dc40-42da-ae53-f10b01a0b197", 
addedDate: "2018-10-08T10:47:46.829258", 
content: "test1"
}, {
id: "ee997e10-919c-42cc-8efb-7ea49cf5c197", 
addedBy: "user22", 
addedById: "1781e165-82f4-4a49-884c-ba66031ad0da", 
addedDate: "2018-10-08T10:41:59.264111", 
content: "test2"}]

我正在尝试使用reduce

过滤和输出评论
const comments = this.props.comments.reduce((result, cm, index) => {
            if(cm.addedById === "3dc8e8a0-dc40-42da-ae53-f10b01a0b197") {
                result += <li key={index} className="task-comments__comment">
                    <p className="task-comments__comment-header">
                        <span className="task-comments__comment-author">{ cm.addedBy }</span>
                        <span
                            className="task-comments__comment-date">
                            {moment(cm.addedDate).format('DD.MM.YYYY HH:MM')}
                        </span>
                    </p>
                    <p className="task-comments__comment-text">
                        { cm.content }
                    </p>
                </li>;
            }
            return result;
        }, {});

但结果我得到了
enter image description here

怎么了?如何解决?

2 个答案:

答案 0 :(得分:1)

您正在串联对象。

相反,result应该是一个数组。

const comments = this.props.comments.reduce((result, cm, index) => {
        if(cm.addedById === "3dc8e8a0-dc40-42da-ae53-f10b01a0b197") {
            result.push(<li key={index} className="task-comments__comment">
                <p className="task-comments__comment-header">
                    <span className="task-comments__comment-author">{ cm.addedBy }</span>
                    <span
                        className="task-comments__comment-date">
                        {moment(cm.addedDate).format('DD.MM.YYYY HH:MM')}
                    </span>
                </p>
                <p className="task-comments__comment-text">
                    { cm.content }
                </p>
            </li>);
        }
        return result;
    }, []);

答案 1 :(得分:1)

由于您没有描述所需的确切内容,因此我做出了一些猜测:

首先让我们使用map创建一个新的修改后的数组,最后让我们使用filter过滤出空数组项,因为映射将创建这些数组项(由于if语句)

最后,我建议将HTML与逻辑分开

const comments = this.props.comments.map((item, index) => {
    if(item.addedById === "3dc8e8a0-dc40-42da-ae53-f10b01a0b197")
        return createListItem(item, index);
}).filter(Boolean);

function createListItem(item, index){
  return <li key={index} className="task-comments__comment">
      <p className="task-comments__comment-header">
          <span className="task-comments__comment-author">{ item.addedBy }</span>
          <span className="task-comments__comment-date">
              {moment(item.addedDate).format('DD.MM.YYYY HH:MM')}
          </span>
      </p>
      <p className="task-comments__comment-text">{ item.content }</p>
  </li>
}