根据相同的值重新组织对象:分步指南
P粉021553460
P粉021553460 2024-04-01 11:40:44
0
2
455

我有 3 个对象

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

我需要按名称对它们进行分组:

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

也许lodash有什么微妙的解决方案?

P粉021553460
P粉021553460

全部回复(2)
P粉928591383

您可以使用Object.values 与 Array.prototype.reduce 结合()Array.prototype .push()

代码:

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

你不需要lodash,你可以只使用JavaScript

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

使用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);

使用减少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);

使用地图和减少

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

输出

console.log(transformedArray);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板