Search code examples
javascripttypescriptecmascript-6destructuringecmascript-2016

Conditional destructuring array of objects es6


stackblitz: demo

The idea is the server sends a response in the below format, based on the following conditions needs to decide to show or hide the button on a page and each button has individual click functions. that's what I have static declare the button in a page.

I have below an array of objects. I need to map the object's properties to other properties with some conditions.

collections = [
  {
    "productId": "samsung",
    "productParams": "",
    "isAvailable": true
  },
  {
    "productId": "nokia",
    "productParams": "",
    "isAvailable": true
  },
  {
    "productId": "Lg",
    "productParams": "",
    "isAvailable": false
  },
]

Here is a collection array of objects. Here I try to map the object's properties based on two conditions,

if productId value matches 'string' and isAvailable property is true I have assigned to a global variable and show the button. But it works wrong. Anyone help the code what I did wrong.

getClick() {
  let showButtonSamsung, showButtonNokia, showButtonLg;
  let x = this.collections.map(x => {
    showButtonSamsung = x.productId == 'samsung' && x.isAvailable == true ? true : false;
    showButtonNokia = x.productId =='nokia' && x.isAvailable == true ? true : false;
    showButtonLg = x.productId == 'Lg' && x.isAvailable == true ? true : false;
  });
}

expected O/P:

showButtonSamsung: true  // will show the button
showButtonNokia: true  // will show the button
showButtonLg: false  // hide the button

Solution

  • I think reduce would be much better in this case.

    let collections = [{
        "productId": "samsung",
        "productParams": "",
        "isAvailable": true
      },
      {
        "productId": "nokia",
        "productParams": "",
        "isAvailable": true
      },
    
      {
        "productId": "Lg",
        "productParams": "",
        "isAvailable": false
      }
    ]
    
    
    const map = {
      samsung: "showButtonSamsung",
      nokia: "showButtonNokia",
      Lg: "showButtonLg"
    }
    
    const {showButtonSamsung, showButtonNokia, showButtonLg} = collections.reduce((acc, obj) => {
      const property = map[obj.productId];
      acc[property] = obj.isAvailable;
      return acc;
    }, {})
    
    console.log(showButtonSamsung, showButtonNokia, showButtonLg);