首页 > 解决方案 > 使用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 教程

标签: javascriptnode.jsarraysreactjstypescript

解决方案


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)


推荐阅读