Search code examples
javascriptecmascript-6javascript-objects

Formatting of JavaScript Objects, Showing Sub Products under Products


I have an array of objects for products I want to show objects that have a parent ID under their parent object with property called subproduct

I have a array object like

let products = [{
        "id": 30,
        "service_provider_id": 4,
        "parent_id": null,
        "status_id": 1,
        "code": "1450",
        "name": "Paypal"
    },
    {
        "id": 31,
        "service_provider_id": 4,
        "parent_id": 30,
        "status_id": 1,
        "code": "1451",
        "name": "Payments"
    }
]

I want to format it in the following way

"products": [{
    "id": 30,
    "service_provider_id": 4,
    "parent_id": null,
    "status_id": 1,
    "code": "14",
    "name": "Paypal"
    "sub-products": [{
        "id": 31,
        "service_provider_id": 4,
        "parent_id": 30,
        "status_id": 1,
        "code": "15",
        "name": "Paypal-Payments"
    }]
}]

Solution

  • This will work

    let products =  [
      {
          "id": 30,
          "service_provider_id": 4,
          "parent_id": null,
          "status_id": 1,
          "code": "1450",
          "name": "Paypal"
      },
      {
          "id": 31,
          "service_provider_id": 4,
          "parent_id": 30,
          "status_id": 1,
          "code": "1451",
          "name": "Payments"
      }
    ]
    
    let formated = [];
    
    formated = products.filter(product => product.parent_id == null);
    
    formated.forEach(formatedproduct=>{
      products.forEach(product =>{
          if(product.parent_id == formatedproduct.id){
            if(!formatedproduct.sub_products )
            {
            formatedproduct.sub_products = [];
            }
            product.name = formatedproduct.name +' '+product.name;
            formatedproduct.sub_products.push(product);
            
            
          }
      });
    })
    
    console.log(formated);