如何在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' ] } ]