如何在 JavaScript 中迭代对象数组并构建新数组?
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的对象数组 −
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' ] } ]