Réorganiser les objets en fonction des mêmes valeurs : un guide étape par étape
P粉021553460
P粉021553460 2024-04-01 11:40:44
0
2
316

J'ai 3 objets

[
{name: 3, q: 10, b: 1},
{name: 5, q: 6, b: 2},
{name: 5, q: 7, b: 1}
]

Je dois les regrouper par nom :

[
{name: 3: items: [{q:10, b: 1}]},
{name: 5: items: [{q:6, b: 2}, {q:7, b: 1}]},
]

Peut-être que Lodash a une solution subtile ?

P粉021553460
P粉021553460

répondre à tous(2)
P粉928591383

Vous pouvez utiliser Object.values combiné avec Array.prototype.reduce() et Array.prototype .push()

Code :

const data = [
  { name: 3, q: 10, b: 1 },
  { name: 5, q: 6, b: 2 },
  { name: 5, q: 7, b: 1 },
]

const groupedData = Object.values(
  data.reduce((acc, obj) => {
    const { name, ...rest } = obj
    acc[name] = acc[name] || { name, items: [] }
    acc[name].items.push(rest)
    return acc
  }, {})
)

console.log(groupedData)
P粉884548619

Vous n'avez pas besoin de lodash, vous pouvez simplement utiliser JavaScript

const inputArray = [
  {name: 3, q: 10, b: 1},
  {name: 5, q: 6, b: 2},
  {name: 5, q: 7, b: 1}
];

Utilisez forEach

function groupItemsByName(array) {
  // create a groups to store your new items
  const groups = {};
  
  //loop through your array
  array.forEach(obj => {
    // destructure each object into name and the rest 
    const { name, ...rest } = obj;
    // if the named group doesnt exist create that name with an empty array
    if (!groups[name]) {
      groups[name] = { name, items: [] };
    }
    // add the items to the named group based on the name
    groups[name].items.push(rest);
  });

  return Object.values(groups);
}

const transformedArray = groupItemsByName(inputArray);

Utilisez reduce et Object.values()

function groupItemsByName(array) {
  //Object.values returns an objects values as an array  
  return Object.values(
    array.reduce((groups, obj) => {
      // destructure as in the forEach method
      const { name, ...rest } = obj;
      // create the groups like in the previous method
      groups[name] = groups[name] || { name, items: [] };
      // push the items to the group based on the name
      groups[name].items.push(rest);
      return groups;
    }, {})
  );
}


const transformedArray = groupItemsByName(inputArray);

Utilisez cartes et réduisez

const transformedArray = Array.from(
  inputArray.reduce((map, obj) => {
    const { name, ...rest } = obj;
    const existing = map.get(name) || { name, items: [] };
    existing.items.push(rest);
    return map.set(name, existing);
  }, new Map()).values()
);

Sortie

console.log(transformedArray);
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!