从下面的数组开始,在JavaScript中,使用Lodash,如何按唯一用户对任务进行分组,以在下面输出“ tasks_by_user”数组?
输入:
tasks: [
{
name: "buy milk",
users: [
"123", "456"
]
},
{
name: "get bread",
users: [
"123"
]
}
]
输出:
tasks_by_user : [
{
user: "123",
tasks: [
{
name: "buy milk"
},
{
name: "get bread"
}
]
},
{
user: "456",
tasks: [
{
name: "buy milk"
}
]
}
]
答案 0 :(得分:1)
您可以使用reduce
和forEach
方法进行操作。
const data = [{"name":"buy milk","users":["123","456"]},{"name":"get bread","users":["123"]}]
let result = _.values(_.reduce(data, (r, {name,users}) => {
_.forEach(users, user => {
if (!r[user]) r[user] = {
user,
tasks: []
}
r[user].tasks.push({name})
})
return r;
}, {}))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
答案 1 :(得分:0)
普通的javascript解决方案。
const data = [{
"name": "buy milk",
"users": ["123", "456"]
}, {
"name": "get bread",
"users": ["123"]
}];
var result = data.reduce((acc, {name, users}) => {
users.forEach(u => {
acc[u] = (acc[u] || []);
acc[u].push(name);
});
return acc;
}, {});
console.log(Object.getOwnPropertyNames(result).map(user => {
return {
user,
tasks: result[user]
};
}));
答案 2 :(得分:0)
您可以使用本机Array.prototype.reduce
通过按用户ID对输入数据进行分组,然后将分组后的对象映射到数组来完成此操作:
const tasks=[{name:"buy milk",users:["123","456"]},{name:"get bread",users:["123"]}];
var dataObj = tasks.reduce((all, {name, users}) => {
users.forEach(user => {
if (!all.hasOwnProperty(user)) all[user] = {user, tasks: []};
all[user].tasks.push({name});
})
return all;
}, {});
var tasks_by_user = Object.keys(dataObj).map(k => dataObj[k]);
console.log(tasks_by_user);
答案 3 :(得分:0)
@trs ,您也可以尝试以下代码。
/* Input array */
var tasks = {tasks: [
{
name: "buy milk",
users: [
"123", "456"
]
},
{
name: "get bread",
users: [
"123"
]
}
]}
var inputArr = tasks['tasks']
/* Creating output array */
var outputArr = []
var outputObj = {}
for(var obj of inputArr){
for(var user of obj["users"]){
var o = {'name': obj['name']}
if(outputObj[user] == undefined){
outputObj[user] = [o]
} else {
outputObj[user].push(o)
}
}
}
console.log(JSON.stringify(outputObj, null, 4))
/*
{
"123": [
{
"name": "buy milk"
},
{
"name": "get bread"
}
],
"456": [
{
"name": "buy milk"
}
]
}
*/
for(var key in outputObj) {
outputArr.push({'user': key, 'tasks': outputObj[key]})
}
console.log(JSON.stringify(outputArr, null, 4))
/*
[
{
"user": "123",
"tasks": [
{
"name": "buy milk"
},
{
"name": "get bread"
}
]
},
{
"user": "456",
"tasks": [
{
"name": "buy milk"
}
]
}
]
*/
最终输出:
[
{
"user": "123",
"tasks": [
{
"name": "buy milk"
},
{
"name": "get bread"
}
]
},
{
"user": "456",
"tasks": [
{
"name": "buy milk"
}
]
}
]