问题描述
data = [
{
"label":"gender","options":[
{"text":"m","value":0},{"text":"f","value":1},{"text":"x","value":null}
]
},{
"label":"age","options":[
{"text":"<30",{"text":"<50",{"text":">50","value":3}
]
}
]
在计算属性中,我想要一个新数组,它看起来与 data prop 完全一样,不同之处在于 - 举例来说 - 我想将 options 数组中的值乘以 2。简单地说js 我以前这样做过,像这样:
data.forEach(item => {
item.options.forEach(option => {
if (option.value !== null && option.value !== 0) {
option.value *= 2;
}
})
});
现在我正在尝试使用 .map() 在计算属性中执行此操作,因此它不会改变我的数据道具,但我不知道如何进行。
computed: {
doubledValues() {
var array = this.data.map((item) => {
//...
item.options.map((option) => {
//... option.value * 2;
});
});
return array;
}
}
解决方法
只需复制对象/数组。会是这样的
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;
});
}
}
,
您可以使用 map()
方法,如下所示:
computed: {
doubledValues() {
return this.data.map(item => ({...item,options: item.options.map(obj => {
return (obj.value != null) ? { ...obj,value: obj.value * 2 } : { ...obj }
})})
);
}
}