1
votes

comment regrouper par propriétés imbriquées à l'aide de lodash?

J'ai un tableau d'objets

let ids: any = groupBy(this.project.work, function (res) {
    return res.employee._id;
});

for (let id in ids) {
    let tmp = [];
    let employee_added = false;
    ids[id].map((work) => {
        if (!employee_added) {
            tmp = work.employee;
            tmp['work'] = [];
            employee_added = true;
        }
        delete work.employee;
        tmp['work'].push(work);
    })

    this.employees.push(tmp);
}

console.log(this.employees);

Je dois les convertir en

[{
    "_id": "5c80c16e0c253823fc44332a",
    "status": "active",
    "location": "Chennai",
    "contact_number": "1234567890",
    "work": [{
        "_id": "5c80c5c00c253823fc443337",
        "start": "2019-01-01T18:30:00.000Z",
        "end": "2019-01-02T18:30:00.000Z",
        "allocation": 30
    }, {
        "_id": "5c80c5ef0c253823fc443339",
        "start": "2018-12-31T18:30:00.000Z",
        "end": "2019-09-30T18:30:00.000Z",
        "allocation": 100
    }, {
        "_id": "5c80c60b0c253823fc44333a",
        "start": "2018-12-31T18:30:00.000Z",
        "end": "2020-10-07T18:30:00.000Z",
        "allocation": 25
    }]
}, {
    "_id": "5c80c1940c253823fc44332b",
    "status": "active",
    "location": "Chennai",
    "contact_number": "1234567890",
    "work": [{
        "_id": "5c80c65e0c253823fc44333b",
        "start": "2019-01-01T18:30:00.000Z",
        "end": "2019-10-04T18:30:00.000Z",
        "allocation": 50
    }]
}, {
    "_id": "5c80c26e0c253823fc44332e",
    "status": "active",
    "location": "Chennai",
    "contact_number": "1234567890",
    "work": [{
        "_id": "5c80c7240c253823fc44333f",
        "start": "2018-12-31T18:30:00.000Z",
        "end": "2019-10-09T18:30:00.000Z",
        "allocation": 25
    }]
}]

Je l'ai fait en utilisant partiellement lodash et vanilla js et cela fonctionne parfaitement. mais la lisibilité est complètement mauvaise. Je veux y parvenir en utilisant uniquement du lodash. Avez-vous de l'aide?

{
    "work": [{
            "_id": "5c80c5c00c253823fc443337",
            "start": "2019-01-01T18:30:00.000Z",
            "end": "2019-01-02T18:30:00.000Z",
            "employee": {
                "_id": "5c80c16e0c253823fc44332a",
                "status": "active",
                "location": "Chennai",
                "contact_number": "1234567890"
            },
            "allocation": 30
        },
        {
            "_id": "5c80c5ef0c253823fc443339",
            "start": "2018-12-31T18:30:00.000Z",
            "end": "2019-09-30T18:30:00.000Z",
            "employee": {
                "_id": "5c80c16e0c253823fc44332a",
                "status": "active",
                "location": "Chennai",
                "contact_number": "1234567890"
            },
            "allocation": 100
        },
        {
            "_id": "5c80c60b0c253823fc44333a",
            "start": "2018-12-31T18:30:00.000Z",
            "end": "2020-10-07T18:30:00.000Z",
            "employee": {
                "_id": "5c80c16e0c253823fc44332a",
                "status": "active",
                "location": "Chennai",
                "contact_number": "1234567890"
            },
            "allocation": 25
        },
        {
            "_id": "5c80c65e0c253823fc44333b",
            "start": "2019-01-01T18:30:00.000Z",
            "end": "2019-10-04T18:30:00.000Z",
            "employee": {
                "_id": "5c80c1940c253823fc44332b",
                "status": "active",
                "location": "Chennai",
                "contact_number": "1234567890"
            },
            "allocation": 50
        },
        {
            "_id": "5c80c7240c253823fc44333f",
            "start": "2018-12-31T18:30:00.000Z",
            "end": "2019-10-09T18:30:00.000Z",
            "employee": {
                "_id": "5c80c26e0c253823fc44332e",
                "status": "active",
                "location": "Chennai",
                "contact_number": "1234567890"
            },
            "allocation": 25
        }
    ]
}


0 commentaires

3 Réponses :


1
votes

Vous pouvez le faire de manière succincte en utilisant du JavaScript brut avec Object.values ​​() , Array.reduce () et déstructurer l'affectation:

const data = {"work":[{"_id":"5c80c5c00c253823fc443337","start":"2019-01-01T18:30:00.000Z","end":"2019-01-02T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":30},{"_id":"5c80c5ef0c253823fc443339","start":"2018-12-31T18:30:00.000Z","end":"2019-09-30T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":100},{"_id":"5c80c60b0c253823fc44333a","start":"2018-12-31T18:30:00.000Z","end":"2020-10-07T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":25},{"_id":"5c80c65e0c253823fc44333b","start":"2019-01-01T18:30:00.000Z","end":"2019-10-04T18:30:00.000Z","employee":{"_id":"5c80c1940c253823fc44332b","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":50},{"_id":"5c80c7240c253823fc44333f","start":"2018-12-31T18:30:00.000Z","end":"2019-10-09T18:30:00.000Z","employee":{"_id":"5c80c26e0c253823fc44332e","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":25}]};

const result = Object.values(data.work.reduce((acc, work) => {
  const { employee: { _id, ...rest }, ...job } = work;
  const jobs = (acc[_id] || {}).work || [];
  acc[_id] = { _id, ...rest, work: [...jobs, job] };
  return acc;
}, {}));

console.log(result);


4 commentaires

Merci pour cela +1 Neat and Clean, Mais je cherche des réponses lodash, de toute façon j'accepterai votre réponse, si je ne pouvais rien trouver avec lodash.


@Thamaraiselvam n'a pas compris pourquoi vous avez accepté la version loadash des réponses (la mienne et celle d'Ori Drori), puis non. cette réponse avec JS simple a l'air bien, puis vous avez demandé lodash versoin (dans le dernier commentaire de cet an), après cela j'ai proposé une solution de lodash (en pensant que cela peut vous aider). Je ne sais pas exactement ce que vous cherchiez.


@KoushikChatterjee vous avez vraiment fait un excellent travail en affichant la meilleure réponse. puisque j'utilise dactylographié, il y a des problèmes de syntaxe avec vos réponses et j'étais pressé, j'ai donc utilisé la réponse jo_va.


@Thamaraiselvam Hmm, en fait, il ne s'agit pas de ma réponse ou de la réponse de quelqu'un, si vous avez un problème, commentez une réponse, vous devriez la commenter, afin d'avoir une image plus grande, pour tous les utilisateurs de SO qui pourraient faire face à ce genre de problème.



2
votes

Vous pouvez créer une fonction qui utilise le _.flow () de lodash qui regroupe par l'identifiant d'employé, puis crée un objet employé avec un tableau de travail:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
const { flow, partialRight: pr, groupBy, map, head, get, omit } = _

const fn = flow(
  pr(groupBy, 'employee._id'),
  pr(map, group => ({ // create the employee objects
    ...get(head(group), 'employee'), // get the employee data and spread it
    work: group.map(o => omit(o, 'employee')) // create the work array by removing the employee from each work object
  }))
)

const data = {"work":[{"_id":"5c80c5c00c253823fc443337","start":"2019-01-01T18:30:00.000Z","end":"2019-01-02T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":30},{"_id":"5c80c5ef0c253823fc443339","start":"2018-12-31T18:30:00.000Z","end":"2019-09-30T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":100},{"_id":"5c80c60b0c253823fc44333a","start":"2018-12-31T18:30:00.000Z","end":"2020-10-07T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":25},{"_id":"5c80c65e0c253823fc44333b","start":"2019-01-01T18:30:00.000Z","end":"2019-10-04T18:30:00.000Z","employee":{"_id":"5c80c1940c253823fc44332b","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":50},{"_id":"5c80c7240c253823fc44333f","start":"2018-12-31T18:30:00.000Z","end":"2019-10-09T18:30:00.000Z","employee":{"_id":"5c80c26e0c253823fc44332e","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":25}]}

const result = fn(data.work)

console.log(result)


2 commentaires

Parfait +1, merci pour cela


@OriDrori Essayez d'éviter omettre , prenez plutôt le reste des attributs comme {employee, ... rest} et utilisez rest



3
votes

J'espère que c'est ce que vous recherchez.

  1. Regroupez-le d'abord par employee_.id
  2. Ensuite, mappez chaque groupe, prenez l'employé du premier (puisque chaque groupe doit avoir une entrée)
  3. Mappez ensuite tous les autres membres (et prenez la partie extérieure) de chaque groupe pour travailler (tout sauf l'objet employé)

Voici l'exemple ci-dessous:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
let works = [{"_id":"5c80c5c00c253823fc443337","start":"2019-01-01T18:30:00.000Z","end":"2019-01-02T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":30},{"_id":"5c80c5ef0c253823fc443339","start":"2018-12-31T18:30:00.000Z","end":"2019-09-30T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":100},{"_id":"5c80c60b0c253823fc44333a","start":"2018-12-31T18:30:00.000Z","end":"2020-10-07T18:30:00.000Z","employee":{"_id":"5c80c16e0c253823fc44332a","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":25},{"_id":"5c80c65e0c253823fc44333b","start":"2019-01-01T18:30:00.000Z","end":"2019-10-04T18:30:00.000Z","employee":{"_id":"5c80c1940c253823fc44332b","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":50},{"_id":"5c80c7240c253823fc44333f","start":"2018-12-31T18:30:00.000Z","end":"2019-10-09T18:30:00.000Z","employee":{"_id":"5c80c26e0c253823fc44332e","status":"active","location":"Chennai","contact_number":"1234567890"},"allocation":25}]


let res = _(works)
            .groupBy('employee._id')
            .map(g => ({...g[0].employee, work: _.map(g, ({employee, ...rest}) => ({...rest}))}))
            .value();
            
console.log(res)


0 commentaires