我如何操纵Javascript数组?

时间:2017-05-04 19:40:56

标签: javascript

我想用样本数据操作数组。

我想要做的是在投票数据中找到movieId,统计它,获取用户的名字

数据说明:

movieId:投票有多个movieIds,但只需要导入一个。

movieIdLength:movieId的总数。

name:具有相同movieId的用户名。

例如:

var votes = [{

    "id": 1,
    "pollId": 1,
    "movieId": 2,
    "name": "James"
}, {
    "id": 2,
    "pollId": 1,
    "movieId": 3,
    "name": "Laura"
}, {
    "id": 3,
    "pollId": 1,
    "movieId": 1,
    "name": "Dan"
}, {
    "id": 4,
    "pollId": 1,
    "movieId": 3,
    "name": "Steve"
}]

我想要的是什么:

var votesResult = [{

    "movieId": 2,
    "movieIdLength": 1,
    "name": "James"
},{
    "movieId": 1,
    "movieIdLength": 1,
    "name": "Dan"
},{
    "movieId": 3,
    "movieIdLength": 2,
    "name": "Laura, Steve"
}]

1 个答案:

答案 0 :(得分:0)

ES6:

const a = [{
    "id": 1,
    "pollId": 1,
    "movieId": 2,
    "name": "James"
}, {
    "id": 2,
    "pollId": 1,
    "movieId": 3,
    "name": "Laura"
}, {
    "id": 3,
    "pollId": 1,
    "movieId": 1,
    "name": "Dan"
}, {
    "id": 4,
    "pollId": 1,
    "movieId": 3,
    "name": "Steve"
}]

const r = [...new Set(a.map(x => x.movieId))]
	.map(x => Object.assign({movieId: x}, 
  	{movieIdLength: a.filter(l => l.movieId === x).length}, 
  	{name: a.filter(q => q.movieId === x).map(n => n.name).join(', ')}));

console.log(JSON.stringify(r, null, 2));

不太清楚,但没有代码重复:

const a = [{
    "id": 1,
    "pollId": 1,
    "movieId": 2,
    "name": "James"
}, {
    "id": 2,
    "pollId": 1,
    "movieId": 3,
    "name": "Laura"
}, {
    "id": 3,
    "pollId": 1,
    "movieId": 1,
    "name": "Dan"
}, {
    "id": 4,
    "pollId": 1,
    "movieId": 3,
    "name": "Steve"
}]

const r = [...new Set(a.map(x => x.movieId))]
  .map(x => Object.assign({movieId: x}, 
  ((f) => Object.assign({movieIdLength: f.length, name: f.map(({name}) => name).join(', ')})
    )(a.filter(({movieId}) => movieId === x))
  ));

console.log(JSON.stringify(r, null, 2));