有条件地破坏对象数组es6。

问题描述 投票:0回答:1

Stackblitz:演示

我的想法是服务器发送一个如下格式的响应,根据以下条件需要决定显示或隐藏页面上的按钮,每个按钮都有单独的点击功能,这就是我在页面中静态声明按钮。

我下面有一个对象数组。我需要用一些条件将对象的属性映射到其他属性上。

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

    {
    "productId": "Lg",
    "productParams": "",
    "isAvailable": false
  },

这里是一个对象的集合数组。

这里我尝试根据两个条件来映射对象的属性。

如果productId值符合'string'并且isAvailable属性为true,我已经分配给一个全局变量并显示按钮。但它的工作是错误的。任何一个人帮助的代码,我做错了什么。

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


  }

预期的OP。

showButtonSamsung : true  // will show the button
showButtonNokia :true  // will show the button
showButtonLg :false  // hide the button:
javascript typescript ecmascript-6 destructuring ecmascript-7
1个回答
2
投票

我想 reduce 在这种情况下会更好。

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

1
投票

我想这多少是你要找的。

 const collections = [
    {
        "productId": "samsung",
        "productParams": "",
        "isAvailable": true
    },
    {
        "productId": "nokia",
        "productParams": "",
        "isAvailable": true
    },

    {
        "productId": "Lg",
        "productParams": "",
        "isAvailable": false
    }];

let isAvailable = (brand, collections) => collections.some((x) => x.productId === brand && x.isAvailable) 

let x = {
    showButtonSamsung: isAvailable('samsung', collections),
    showButtonNokia: isAvailable('nokia', collections),
    showButtonLg: isAvailable('Lg', collections),
}
console.log(x);

另一个选择

let x = {
    showButtonSamsung: 'samsung',
    showButtonNokia: 'nokia',
    showButtonLg: 'Lg',
}


let isAvailable = (brand, collections) => collections.some((x) => x.productId === brand && x.isAvailable)
x = Object.entries(x).map(([key, value]) => ([key, isAvailable(value, collections)]))
    .reduce((obj, arr) => ({
        ...obj, [arr[0]]: arr[1]
    }), {})

console.log(x);
© www.soinside.com 2019 - 2024. All rights reserved.