我想遍历集合,但是由于我是新手,所以我很难做到这一点。下面显示了我的数据。
user: Array [1]
0. Object
id:8
products:Object
3: Array[2]
0: Object
value: 25
id:4
1: Object
value: 20
id:5
4: Array[3]
0: Object
value: 14
id:6
1: Object
value: 30
id:7
1: Object
value: 20
id:8
所以我想获取价值,以便对每个分组的集合进行求和。集合3的总和= a,集合4的总和= b,依此类推。
我尝试如下,但一无所获:
data:{
user:[],
}
methods:{
watchedOnly(){
var self = this;
for(var product in self.user.products ){
for (var key in product){
if(product.hasOwnProperty('key')){
console.log(product[key]);
}
}
}
}, }
有人可以帮我吗?
答案 0 :(得分:0)
首先,如果您的真实数据具有这样的结构,请发表评论,然后编辑此答案:
let user = [
{
id: 8,
products: {
3: [
{id: 4, value: 25},
{id: 5, value: 20}
],
4: [
{id: 6, value: 14},
{id: 7, value: 30},
{id: 8, value: 20}
]
}
}
]
function sum (arr) {
Object
.entries(arr[0].products)
.forEach(pair => {
let sum = Array
.from(pair[1].map(o => o.value))
.reduce((a, b) => a + b)
console.log(`Sum for product ${pair[0]} is ${sum}`)
})
}
sum(user)
或在Vue组件中:
export default {
data () {
return {
user: []
}
},
computed: {
watchedOnly () {
let result = {}
Object
.entries(this.user[0].products)
.forEach(pair => {
let sum = Array
.from(pair[1].map(o => o.value))
.reduce((a, b) => a + b)
result[pair[0]] = sum
})
return result
}
}
}
在模板中使用它:
<p v-for="(sum, product) in watchedOnly">
Sum for product {{ product }} is {{ sum }}
</p>