如何在 JavaScript 中迭代对象数组并构建一个新数组?
假设我们有一个如下所示的对象数组 −
const arr = [ { "customer": "Customer 1", "project": "1" }, { "customer": "Customer 2", "project": "2" }, { "customer": "Customer 2", "project": "3" } ]
我们要求编写一个 JavaScript 函数,该函数获取这样一个数组,并生成(返回)一个新数组。
在新数组中,所有具有相同值的用户密钥应该合并,输出应该类似于如下形式 −
const output = [ { "Customer 1": { "projects": "1" } }, { "Customer 2": { "projects": [ "2", "3" ] } } ]
示例
让我们写代码 −
const arr = [ { "customer": "Customer 1", "project": "1" }, { "customer": "Customer 2", "project": "2" }, { "customer": "Customer 2", "project": "3" } ] const groupCustomer = data => { const res = []; data.forEach(el => { let customer = res.filter(custom => { return el.customer === custom.customer; })[0]; if(customer){ customer.projects.push(el.project); }else{ res.push({ customer: el.customer, projects: [el.project] }); }; }); return res; }; console.log(groupCustomer(arr));
输出
并且控制台中输出将类似如下形式 −
[ { customer: 'Customer 1', projects: [ '1' ] }, { customer: 'Customer 2', projects: [ '2', '3' ] } ]
广告