Home > other >  Generate dynamic payload as per nested array item click javascript
Generate dynamic payload as per nested array item click javascript

Time:05-21

hi i have below JSON formate

{
 "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"
    }
    ]
   }
  ]
 }

I have tagview in my mobile screen so user can select multiple subcategory at a same time by select deselect so if i choose 2 subcatery from Art and 2 from Bussines then expected post payload shoub be like below

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

] }

So my code is like below

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;
    })

When i run above code payload is not passing correct

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

It is passing all selected subcategory in both array any idea how can i solve this ?

CodePudding user response:

If you have the selected tag ids in the array selectedTags and your json as a variable called 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

  • Related