简体   繁体   English

没有变异道具的双 for 循环,VUE3

[英]Double for loop without mutating prop, VUE3

I have a 'data' props which say looks like this:我有一个“数据”道具,它看起来像这样:

data = [
    {
      "label":"gender",
      "options":[
        {"text":"m","value":0},
        {"text":"f","value":1},
        {"text":"x", "value":null}
      ]
    },
    {
      "label":"age",
      "options":[
        {"text":"<30", "value":0},
        {"text":"<50","value":1},
        {"text":">50","value":3}
      ]
    }
  ]

In a computed property I want to have a new array which looks exactly like the data prop, with the difference that - for the sake of example let's say - I want to multiply the value in the options array by 2. In plain js I did this before, like this:在一个计算属性中,我想要一个看起来与 data 属性完全一样的新数组,不同之处在于——为了举例说明——我想将选项数组中的值乘以 2。在普通的 js 中我做了这个之前,像这样:

data.forEach(item => {
    item.options.forEach(option => {
      if (option.value !== null && option.value !== 0) {
        option.value *= 2;
      }
    })
  });

Now I'm trying to do this in a computed property, with.map(), so it doesn't mutate my data props, but I cant figure out how.现在我试图在计算属性 with.map() 中执行此操作,因此它不会改变我的数据道具,但我不知道如何。

computed: {
  doubledValues() {
    var array = this.data.map((item) => {
      //...
      item.options.map((option) => {
        //... option.value * 2;
      });
    });
    return array;
  }
}

Just copy objects/arrays.只需复制对象/数组。 It will be something like that会是这样的

computed: {
  doubledValues() {
    return this.data.map((item) => {
      const resultItem = {...item};
      resultItem.options = item.options.map((option) => {
        const copyOption = {...option};
        if (copyOption.value !== null && copyOption.value !== 0) {
          copyOption.value *= 2;
        }
        return copyOption;
      });
      return resultItem;
    });
  }
}

you can use map() method, like so:您可以使用map()方法,如下所示:

computed: {
doubledValues() {
  return this.data.map(item => ({...item, options: item.options.map(obj => {
    return (obj.value != null) ? { ...obj, value: obj.value * 2 } : { ...obj }
  })})
  );
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM