根据嵌套数组项生成动态负载点击 javascript

Generate dynamic payload as per nested array item click javascript

嗨,我有以下 JSON 甲酸盐

{
 "data": [
  {
  "category": {
    "documentId": "c8kr0cv012vtr8vm3iug",
    "title": "Art"
  },
  "subcategories": [
    {
      "documentId": "c8kr7nv012vtr8vm3l8g",
      "title": "Architecture"
    },
    {
      "documentId": "c8kr7nv012vtr8vm3lag",
      "title": "Dance"
    },
    {
      "documentId": "c8kr7nv012vtr8vm3lbg",
      "title": "Fashion"
    }
  ]
},
{
  "category": {
    "documentId": "c8kr0cv012vtr8vm3iqg",
    "title": "Business"
  },
  "subcategories": [
    {
      "documentId": "c8kr3d7012vtr8vm3jjg",
      "title": "Crypto"
    },
    {
      "documentId": "c8kr3d7012vtr8vm3jj0",
      "title": "Finance"
    },
    {
      "documentId": "c8kr3d7012vtr8vm3jkg",
      "title": "Marketing"
    }
    ]
   }
  ]
 }

我的手机屏幕上有 tagview,因此用户可以通过 select deselect 同时 select 多个子类别,所以如果我从 Art 选择 2 个子类别,从 Bussines 选择 2 个然后预期 post 有效负载应该如下所示

{
"data": [
{
  "category": "c8kr0cv012vtr8vm3iug",
  "subcategories": [
    "c8kr7nv012vtr8vm3l8g",
    "c8kr7nv012vtr8vm3lag"
  ]
},
{
  "category": "c8kr0cv012vtr8vm3iqg",
  "subcategories": [
    "c8kr3d7012vtr8vm3jjg",
    "c8kr3d7012vtr8vm3jj0"
   ]
 }

] }

所以我的代码如下

const tempDefaultPayload = dataPayload.map(x => {
    
      if (x.category) {
       x.subcategories?.push(subcategory);
         
        if (userData?.userInterests?.map(v => v.category.documentId === category)) {
          const arrayNewData: any = [];
          const newData: any = userData?.userInterests?.map(i =>
            i.subcategories?.map(k => {
              arrayNewData.push(k?.documentId);
              return k?.documentId;
            }),
          );
          x.subcategories?.push(...arrayNewData);
        }
        return x;
      }
      return x;
    })

当我 运行 上面的代码有效载荷没有正确传递时

[
 {
  "category": "c8kr0cv012vtr8vm3iug",
  "subcategories": [
  "c8kr7nv012vtr8vm3l8g",
  "c8kr7nv012vtr8vm3lag",
  "c8kr3d7012vtr8vm3jjg",
  "c8kr3d7012vtr8vm3jj0"
  ]
},
{
"category": "c8kr0cv012vtr8vm3iqg",
"subcategories": [
  "c8kr7nv012vtr8vm3l8g",
  "c8kr7nv012vtr8vm3lag",
  "c8kr3d7012vtr8vm3jjg",
  "c8kr3d7012vtr8vm3jj0"
  ]
}
]

它正在传递两个数组中的所有 selected 子类别,我知道如何解决这个问题吗?

如果您在数组 selectedTags 中选择了标记 ID,并且您的 json 作为一个名为 data 的变量:

const tempDefaultPayload = {
  data: data.data.map(x => {
       "category": x.category.documentId,
       "subcategories": x.subcategories.map(subcat => 
       subcat.documentId).filter(item => selectedTags.includes(item))    
  })
}

Playground example