简体   繁体   中英

How to group items in array inside another array

We have an array with items:

const array = [object1, object2, ...]

The type of the item is like this:

type Item = {
  id: number;
  title: string
  contact: {
    id: number;
    name: string;
  };
  project: {
    id: number;
    name: string;
  } | null;
};

What we want to archieve is an array structured like this:

type Contact = {
  id: number;
  name: number;
  project: Array<{
    id: number;
    name: number;
    items: Array<{
      id: number;
      title: number;
    }>;
  }>;
};

const array2 = [contact1, contact2, ...]

In Item if it has a project then the project belongs to the contact of that item.

What is an efficient way of mapping this?

At your command!

function extractIdName(obj){
    return {id:obj.id,name:obj.name}
}

function restructure(arr){
    let o={}
    arr.forEach(e=>{
        console.log(e);
        if(!o[e.contact.id]) {
            o[e.contact.id] = extractIdName(e.contact);
            o[e.contact.id].project=[];
        }
        console.log(o[e.contact.id]);
        let ps=o[e.contact.id].project;
        let p = ps.find(project=>{
            return project.id==e.project.id;
        })
        if(!p) {
            p=extractIdName(e.project);
            p.items=[];
            ps.push(p);
        };
        console.log(p);
        p.items.push({id:e.id,title:e.title})
    })
    return Object.values(o);
}
console.log(restructure(array));

It would be more efficient if you use also a ordered map to check existence of projects and contacts but it's not terrible this way if a single contact do not have most of the projects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM