我有两个数组。一种是想法,另一种是评论者。
['idea1', 'idea2', 'idea3', 'idea4', 'idea5', 'idea6', 'idea7']
['reviewer1', 'reviewer2', 'reviewer3', 'reviewer4']
我需要从以上两个数组生成一个数据对象,以将其馈送到表中。在生成对象时需要帮助。
[ {
fields: {
"Idea": "idea1",
"Reviewer": "reviewer1"
}, fields: {
"Idea": "idea2",
"Reviewer": "reviewer2"
}, fields: {
"Idea": "idea3",
"Reviewer": "reviewer3"
}, fields: {
"Idea": "idea4",
"Reviewer": "reviewer4"
}, fields: {
"Idea": "idea5",
"Reviewer": "reviewer1"
}, fields: {
"Idea": "idea6",
"Reviewer": "reviewer2"
}, fields: {
"Idea": "idea7",
"Reviewer": "reviewer3"
},
}]
一个评论者将被分配给多个创意,但是对于任何一个创意,只有一个评论者。
答案 0 :(得分:3)
类似这样的东西:
const idea = ['idea1', 'idea2', 'idea3', 'idea4', 'idea5', 'idea6', 'idea7']
const reviewer = ['reviewer1', 'reviewer2', 'reviewer3', 'reviewer4']
let ctr =0;
const res = idea.reduce((acc, val)=>{
ctr= ctr=== reviewer.length? 0 : ctr;
acc = [...acc, {"fields":{
"idea": val,
"reviewer": reviewer[ctr++]
}}];
return acc
},[])
console.log(res)
不需要变异ctr
的一种更好,更简单的方法是
var idea = ['idea1', 'idea2', 'idea3', 'idea4', 'idea5', 'idea6', 'idea7'];
var reviewer = ['reviewer1', 'reviewer2', 'reviewer3', 'reviewer4'];
var res = idea.map((idea, i) => {
return {
fields: {
idea,
reviewer: reviewer[i % reviewer.length]
}
}
});
console.log(res)