[英]How to print multiple items of a JS object/array in per iteration with map?
I am working in React.我在 React 工作。 I am trying to find out a solution to a mapping problem.我正在尝试找出映射问题的解决方案。 While mapping an object or array in javascript, we know it delivers one item of the array/ object in per iteration.在 javascript 中映射对象或数组时,我们知道它在每次迭代中传递数组/对象的一项。 For Example:例如:
Consider an array of object like:考虑一个对象数组,例如:
const items = [
{
id: 1,
color: "red"
},
{
id: 2,
color: "blue"
},
{
id: 3,
color: "yellow"
},
{
id: 4,
color: "black"
}
];
Now,现在,
items.map((item, i) => <p key={i}>{item.color}</p>)
This will show an output like :这将显示如下输出:
red
blue
yellow
black
Now what if I want to bring multiple items in per iteration.现在如果我想在每次迭代中引入多个项目怎么办。 For Example:例如:
red blue
yellow black
How to do it ?怎么做 ? Thanks in advance.提前致谢。 Please feel free to use this codesandbox example:请随意使用此代码和框示例:
https://codesandbox.io/s/musing-cloud-gnnye?file=/src/App.js:100-339 https://codesandbox.io/s/musing-cloud-gnnye?file=/src/App.js:100-339
This action called "chunk" I would do:这个称为“块”的动作我会做:
import chunk from "lodash.chunk";
const colors = items.map(({ color }, i) => color);
const chunked = chunk(colors, 2);
const renderPairs = chunked.map(([first, second], i) => (
<p key={i}>
{first},{second}
</p>
));
https://codesandbox.io/s/spring-forest-0pvvq?file=/src/App.js:86-679 https://codesandbox.io/s/spring-forest-0pvvq?file=/src/App.js:86-679
Lodash implementation : Lodash 实现:
function chunk(array, size = 1) {
size = Math.max(toInteger(size), 0)
const length = array == null ? 0 : array.length
if (!length || size < 1) {
return []
}
let index = 0
let resIndex = 0
const result = new Array(Math.ceil(length / size))
while (index < length) {
result[resIndex++] = slice(array, index, (index += size))
}
return result
}
You could use the second argument provided by map
function which is the current index of the array to find the next item in the array and print accordingly.您可以使用map
函数提供的第二个参数,即数组的当前索引来查找数组中的下一项并相应地打印。
You could see the working example here :- https://codesandbox.io/s/mystifying-mccarthy-7fc3o?file=/src/App.js你可以在这里看到工作示例:- https://codesandbox.io/s/mystifying-mccarthy-7fc3o?file=/src/App.js
const iterate = items.map((item, i) => {
if (i % 2 !== 0) return null;
const next = items[i + 1] ? items[i + 1].color : "";
return (
<p key={i}>
{item.color} {next}
</p>
);
})
// you could filter or not, it's up to you. React automatically discards null value
.filter(x => x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.