代码之家  ›  专栏  ›  技术社区  ›  arunmmanoharan

将数组数组转换为分组在一起的对象数组

  •  3
  • arunmmanoharan  · 技术社区  · 6 年前

    我有一个数组。如何将它们转换为分组在一起的对象数组?

    var abc = [
      ['apple', 'fruit'], ['banana', 'fruit'], ['grapes', 'fruit'], ['red', 'color'], ['blue', 'color'], ['black', 'color']
    ]
    
    
    abc = abc.map(function(item) {
      return {
        value: item[0],
        color: item[1]
      }
    })
    
    colors = abc.filter(function(item) {
      return item.color === 'color'
    })
    
    fruits = abc.filter(function(item) {
      return item.color === 'fruit'
    })
    
    var result = [{
      group: 'color',
      value: colors.map(function(item) {
        return item.value
      })
    }, {
      group: 'fruit',
      value: fruits.map(function(item) {
        return item.value
      })
    }]
    
    console.log(result)

    var abc = [
    {
        group: 'color',
        value: ['red', 'blue', 'black']
    },
    {
        group: 'fruit',
        value: ['apple', 'banana', 'grapes']
    }]
    

    有没有更简单的方法来实现这一点?

    我也可以用洛达斯。请告知。

    6 回复  |  直到 6 年前
        1
  •  2
  •   Nina Scholz    6 年前

    可以按索引对lodash进行分组,并映射其他索引的值。

    var data = [['apple', 'fruit'], ['banana', 'fruit'], ['grapes', 'fruit'], ['red', 'color'], ['blue', 'color'], ['black', 'color']],
        result = _(data)
            .groupBy(1)
            .map((array, group) => ({ group, value: _.map(array, 0) }))
            .sortBy('group')
            .value();
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
        2
  •  4
  •   ggorlen Hoàng Huy Khánh    6 年前

    这里有一种方法 reduce map . 减少 group 映射到值数组。 Object.entries() 将此分组作为对象数组转换为所需的格式。

    var abc = [
      ['apple', 'fruit'],
      ['banana', 'fruit'],
      ['grapes', 'fruit'],
      ['red', 'color'],
      ['blue', 'color'],
      ['black', 'color']
    ];
    
    const result = Object.entries(
        abc.reduce((a, e) => {
          if (!(e[1] in a)) {
            a[e[1]] = [];
          }
    
          a[e[1]].push(e[0]);
          return a;
        }, {})
      ).map(e => ({group: e[0], value: e[1]}))
    ;
    
    console.log(result);
        3
  •  1
  •   Patryk Cieszkowski    6 年前

    以下是我在对你问题的评论中描述的一种方法:

    1. 循环遍历所有元素,并创建一个空数组
    2. group
    3. 如果找到,则扩展元素
    4. 如果找不到,就创建它

      abc.reduce((arr, input) => {
        const index = arr.findIndex(i => i.group === input[0])
      
        return [
          ...(index > -1
            ? [
              ...arr.slice(0, index),
              {
                group: input[0],
                value: [
                  ...arr[index].value,
                  input[1]
                ]
              },
              ...arr.slice(index + 1)
            ] : [
              ...arr,
              {
                group: input[0],
                value: [ input[1] ]
              }
            ])
        ]
      }, [])
      
        4
  •  1
  •   trincot Jakube    6 年前

    Map 作为中间数据结构:

    var abc = [['apple', 'fruit'],['banana', 'fruit'],['grapes', 'fruit'],['red', 'color'],['blue', 'color'],['black', 'color']];
        
    const groups = new Map(abc.map(a =>[a[1], []]));
    abc.forEach(a => groups.get(a[1]).push(a[0]));
    const result = Array.from(groups, ([group, values]) =>  ({group, values}));
    
    console.log(result);
        5
  •  0
  •   Jonas Wilms    6 年前

    您可以建立一个hashtavle来查找重复的描述符:

     const result = [], hash = {};
    
     for(const [value, group] of abc) {
      if(hash[group]) {
       hash[group].push(value);
      } else {
       result.push({ group, value: (hash[group] = [value]), });
      }
    }
    
        6
  •  0
  •   Tomas    6 年前

    reduce

    var abc = [
      ['apple', 'fruit'],
      ['banana', 'fruit'],
      ['grapes', 'fruit'],
      ['red', 'color'],
      ['blue', 'color'],
      ['black', 'color']
    ]
    
    var r = abc.reduce((prev, curr) => {
      if(prev.findIndex(p => p.group === curr[1]) === -1) {
        prev = prev.concat({group: curr[1], value: []})
      }
      let idx = prev.findIndex(p => p.group === curr[1])
      prev[idx].value.push( curr[0] )
      return prev;
    }, [])
    
    console.log(r)