Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Duyệt mảng đối tượng và xây dựng mảng mới - JavaScript


Giả sử mảng đối tượng:

const arr = [ 
  { "customer": "Customer 1", "project": "1" }, 
  { "customer": "Customer 2", "project": "2" }, 
  { "customer": "Customer 2", "project": "3" } 
]

Viết hàm gom nhóm theo customer, output:

const output = [ 
  { "Customer 1": { "projects": "1" } }, 
  { "Customer 2": { "projects": ["2", "3"] } } 
]

Ví dụ

Mã minh họa:

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 => 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));

Kết quả

Đầu ra:

[ 
  { customer: 'Customer 1', projects: [ '1' ] }, 
  { customer: 'Customer 2', projects: [ '2', '3' ] } 
]