簡體   English   中英

如何使用父對象中的 ID 引用將主對象與子對象合並到每個子對象

[英]How to merge Primary object with child objects using and ID reference in Parent to each child

我有一個主要的父集合(項目)和 2 個存儲為對象數組的子集合。

項目

const projects = {
  items: [
    {
      name: "Logo and Branding for Iron Kettle",
      skills: [
        "579b150756ea2dba79c1f09f",
        "579b150756ea2dba79c1f062"
      ],
      solutions: [
        "579b150756ea2dba79c1f09e",
        "579b150756ea2dba79c1f077"
      ],
      _cid: "579b150756ea2dba79c1efcb",
      _id: "579b150756ea2dba79c1f0af"
    },
    {
      name: "Snow shoot for media company",
      skills: [
        "579b150756ea2dba79c1f072",
        "579b150756ea2dba79c1f062"
      ],
      solutions": [
        "579b150756ea2dba79c1f09e",
        "579b150756ea2dba79c1f071",
      ],
      _cid: "579b150756ea2dba79c1efcb",
      _id: "579b150756ea2dba79c1f06a"
    }
  ],
  count: 12,
  limit: 100,
  offset: 0,
  total: 12
};

技能

const skills = {
  items: [
    {
      name: "Logo Design",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f09f"
    },
    {
      name: "Brand Research",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f072"
    },
    {
      name: "Graphic Design",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f062"
    }
  ],
  count: 13,
  limit: 100,
  offset: 0,
  total: 13
};

解決方案

const solutions = {
  items: [
    {
      name: "Location research",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f09e"
    },
    {
      name: "Complete photo shoot",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f071"
    },
    {
      name: "Competition Analysis",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f077"
    }
  ],
  count: 19,
  limit: 100,
  offset: 0,
  total: 19
};

我需要返回一個新的項目數組,其中的技能和解決方案 ID 填充了相關數組中的實際對象。

這將是新數組中一項的最終結果。

{
  name: "Logo and Branding for Iron Kettle",
  skills: [
    {
        name: "Logo Design",
        _cid: "579b150756ea2dba79c1efdf",
        _id: "579b150756ea2dba79c1f09f"
    },
    {
      name: "Graphic Design",
      _cid: "579b150756ea2dba79c1efdf",
      _id: "579b150756ea2dba79c1f062"
    }
  ],
  solutions: [
    {
      name: "Location research",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f09e"
    },
    {
      name: "Competition Analysis",
      _cid: "579b150756ea2dba79c1eff3",
      _id: "579b150756ea2dba79c1f077"
    }
  ],
  _cid: "579b150756ea2dba79c1efcb",
  _id: "579b150756ea2dba79c1f0af"
},

嘗試這樣的事情:

projects.items.map(i => ({
    ...i,
    skills: i.skills.map(s => skills.items.find(skill => skill._id === s)),
    solutions: i.solutions.map(s => solutions.items.find(solution => solution._id === s))
}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM