[英]How do I group values present under a key in all objects in an array of JSON, under a single key?
I have an array of JSON like:我有一个 JSON 数组,例如:
[
{user_id:1, name: "Person A", project: "Project A"},
{user_id:1, name: "Person A", project: "Project B"},
{user_id:2, name: "Person B", project: "Project A"},
{user_id:2, name: "Person B", project: "Project C"},
{user_id:3, name: "Person C", project: "Project D"}
]
I want to transform this array such that there's only one entry for a person and it has an array with value active_projects or something with all his projects.我想转换这个数组,使得一个人只有一个条目,并且它有一个值为active_projects的数组,或者他所有的项目。 Basically I want to remove the redundancy in this array.
基本上我想删除这个数组中的冗余。 The output would be:
output 将是:
[
{user_id:1, name: "Person A", active_projects: ["Project A","Project B"] },
{user_id:2, name: "Person B", active_projects: ["Project A","Project C"] },
{user_id:3, name: "Person C", active_projects: ["Project D"] }
]
What is the cleanest and best approach for this?什么是最干净和最好的方法?
A simple solution would be to first compute a map of the user_ids using reduce
.一个简单的解决方案是首先使用
reduce
计算 user_ids 的 map。 Then simply use Object.values
to turn it into an array.然后只需使用
Object.values
将其转换为数组。
const lkp = data.reduce((acc, {user_id, name, project}) => { acc[user_id] = acc[user_id] || {}; acc[user_id].user_id = user_id; acc[user_id][name] = name; acc[user_id].active_projects = acc[user_id].active_projects || []; acc[user_id].active_projects.push(project); return acc; }, {}) const arr = Object.values(lkp) console.log(arr)
<script> var data = [ {user_id:1, name: "Person A", project: "Project A"}, {user_id:1, name: "Person A", project: "Project B"}, {user_id:2, name: "Person B", project: "Project A"}, {user_id:2, name: "Person B", project: "Project C"}, {user_id:3, name: "Person C", project: "Project D"} ]; </script>
You can try reduce
method of JavaScript.您可以尝试
reduce
JavaScript 的方法。
var data =[ {user_id:1, name: "Person A", project: "Project A"}, {user_id:1, name: "Person A", project: "Project B"}, {user_id:2, name: "Person B", project: "Project A"}, {user_id:2, name: "Person B", project: "Project C"}, {user_id:3, name: "Person C", project: "Project D"}]; result = Object.values(data.reduce((acc, {user_id, project, ...rest})=>{ acc[user_id] = acc[user_id] || { user_id, ...rest }; acc[user_id].activeProject = acc[user_id].activeProject || []; acc[user_id].activeProject.push(project); return acc; },{})); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.