如何成对包装由对象数组填充的元素

How to wrap elements populated by array of objects in pairs

具有以下对象数组:

const items = [
  {
    description = 'first description'
  },
  {
    description = 'second description'
  },
  {
    description = 'third description'
  },
  {
    description = 'fourth description'
  },
  ...
]

使用地图表示描述很容易:

{
  items.map((item) => (     
    <div>item.description</div>
  ));
}

这将输出以下内容:

<div>first description</div>
<div>second description</div>
<div>third description</div>
<div>fourth description</div>
...

但是我需要为每对元素添加一个容器,所以输出应该是这样的:

<div className="container">
  <div>first description</div>
  <div>second description</div>
</div>
<div className="container">
  <div>third description</div>
  <div>fourth description</div>
</div>
...

我做了以下解决方案,但理解起来很复杂,我认为必须有一个更清晰的解决方案:

{
  let result = [];
  let counter = 0;
  items.forEach((item, index) => {
    if (items.length / 2 > index) {
      result[index] = ( 
        <div className="container">
          <div>items[counter]</div>
          <div>items[counter+1]</div>
        </div>
      );
      counter = counter + 2;
    }
  })
}
{result.map((item) => item)}

有什么建议吗?

这是一个更简洁的解决方案,可以满足您的需求:

const items = [
  {
    description: 'first description'
  },
  {
    description: 'second description'
  },
  {
    description: 'third description'
  },
  {
    description: 'fourth description'
  },
];

function pair(arr, number = 2) {
  return arr.reduce(
    (acc, cur, i) =>
      i % number
        ? Object.assign([...acc], {
            [acc.length - 1]: [...acc[acc.length - 1], cur],
          })
        : [...acc, [cur]],
    []
  );
}

function Render() {
  return <React.Fragment>
    {pair(items).map(x => <div className="container">{x.map(y => <div>{y.description}</div>)}</div>)}
  </React.Fragment>;
}

ReactDOM.render(
  <Render />,
  document.getElementById("react")
);
.container {
  border: 1px solid red;
  margin: 10px;
}
<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>