javascript - 使用reduce转换一个2 js对象2 1
问题描述
我想写一个函数来传输这些对象
const input1 = [
{
id: "lkhj68C13h8uWh4RJz7",
post: "on XSS attacks",
gender: "Littérature",
postId: "cxTbP5EZjNCxw7rD60L7",
},
{
id: "Kek4ulyC13h8uWh4RJz7",
post: "The Maze",
gender: "Littérature",
postId: "cxTbP5EZjNCxw7rD60L7",
},
{
id: "arfstlyC13h8uWh4RJz7",
post: "Runner",
gender: "Littérature",
postId: "92poye7CF0aprDKcYh1Q",
},
];
const input2 = [
{
postId: "92poye7CF0aprDKcYh1Q",
postName: "Attalib",
postUrl: "attalib",
ville: "Casablanca",
},
{
postId: "cxTbP5EZjNCxw7rD60L7",
postName: "Atlas",
postUrl: "atlas",
ville: "Casablanca",
},
];
成为那样的东西
const output = [
{
postId: "92poye7CF0aprDKcYh1Q",
postName: "Attalib",
postUrl: "attalib",
ville: "Casablanca",
posts: [
{
id: "arfstlyC13h8uWh4RJz7",
post: "Runner",
gender: "Littérature",
},
],
},
{
postId: "cxTbP5EZjNCxw7rD60L7",
postName: "Atlas",
postUrl: "atlas",
ville: "Casablanca",
posts: [
{
id: "Kek4ulyC13h8uWh4RJz7",
post: "The Maze",
gender: "Littérature",
},
{
id: "lkhj68C13h8uWh4RJz7",
post: "on XSS attacks",
gender: "Littérature",
},
],
},
];
我尝试使用 Array.reduce,但我不知道如何渲染它。如果有人对此有任何后见之明,我想使用 postid 合并两个输入,那么我可以使用 map 来循环或减少吗,如果有人可以帮助我这样做,我将非常感激,如果你有任何 reduce/map 教程
解决方案
const input1 = [
{
id: "lkhj68C13h8uWh4RJz7",
post: "on XSS attacks",
gender: "Littérature",
postId: "cxTbP5EZjNCxw7rD60L7",
},
{
id: "Kek4ulyC13h8uWh4RJz7",
post: "The Maze",
gender: "Littérature",
postId: "cxTbP5EZjNCxw7rD60L7",
},
{
id: "arfstlyC13h8uWh4RJz7",
post: "Runner",
gender: "Littérature",
postId: "92poye7CF0aprDKcYh1Q",
},
];
const input2 = [
{
postId: "92poye7CF0aprDKcYh1Q",
postName: "Attalib",
postUrl: "attalib",
ville: "Casablanca",
},
{
postId: "cxTbP5EZjNCxw7rD60L7",
postName: "Atlas",
postUrl: "atlas",
ville: "Casablanca",
}];
const final = input2.reduce((acc, current) => {
let filtered = input1.filter(obj => obj.postId === current.postId).map(({id,
post,
gender,
postId}) => { return {id,
post,
gender}});
current.posts = filtered;
acc.push(current);
return acc;
}, []);
console.log(final)
推荐阅读
- regex - 为 ['Cat '(optional) Dog (.*?)] 的条件匹配创建正则表达式 | ['Cat'(可选) (.*?) Dog]
- testing - 如何模拟 ImagePicker
- python - ValueError : 层 lstm 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,18]
- java - 内存非常大的机器上的 OpenJDK MaxRAMPercentage
- python - pyqt5 qwebenginview 不会自动播放 youtube 视频
- scala - 使用 spark scala 中的元组列表过滤数据框
- angular - 为什么我得到未捕获的异常:使用 Jasmine 和 Karma 运行 Angular 规范文件时内存不足
- javascript - Mapbox静态图片Url生成的图片与DOM上的canvas不同
- c# - 仅检测 Unity 中的特定键盘组合
- git - 为什么最好使用 rebase 而不是 merge 来解决维护者的冲突?