搜尋

首頁  >  問答  >  主體

根據相同的值重新組織物件:逐步指南

我有 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粉021553460P粉021553460265 天前464

全部回覆(2)我來回復

  • P粉928591383

    P粉9285913832024-04-02 09:52:41

    您可以使用Object.values< /a> 與 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)

    回覆
    0
  • P粉884548619

    P粉8845486192024-04-02 09:31:42

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

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

    使用forEach< /p>#

    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()< /p>

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

    回覆
    0
  • 取消回覆