【问题标题】:Destructure Array using entries and iterator使用条目和迭代器解构数组
【发布时间】:2020-05-27 15:51:07
【问题描述】:

我有一个对象数组。每个对象都有相同的属性。我尝试创建一个函数来返回一个数组数组,其中每个内部数组都应包含基于对象属性名称的值。

输入:

input: [
    {
       test1: '10',
       test2: '15',
       test3: '14',
       test4: '22'
    },
    {
       test1: '4',
       test2: '1',
       test3: '45',
       test4: '2'
    },
    {
       test1: '5',
       test2: '16',
       test3: '7',
       test4: '0'
    }
]

预期输出 - 数组内部仅包含键相同的元素。 例如test1数组中的值:[10, 4, 5]

output: [[10, 4, 5], [15, 1, 16], [14, 45, 7], [22, 2, 0]]

我的方法是使用 array.entries() 和迭代器。结果是错误的 - 值的存储顺序错误。

let output = [];
sort(input) {
    const results = [[], [], [], []];
    if (input.length > 0) {
      const iterator = input.entries();
      let item = iterator.next();
      while (!item.done) {
        const data = Object.values(item.value[1]);
        results.forEach((result, index) => {
          if (item.value[0] == index)
            result.push(parseFloat(data[index]));
        });
        item = iterator.next();
      }
    }
    output = results;
  }

如何让它发挥作用?

【问题讨论】:

  • 你想如何指定输出的顺序?例如,数组中第一个对象的顺序是什么?

标签: javascript arrays


【解决方案1】:

这是一种技术,它只是使用第一个对象的键顺序来确定最终的输出顺序:

const restructure = (input = []) => 
  Object .keys (input [0] || {}) 
    .map (k => input .map (x => x [k]))

const input = [{test1: '10', test2: '15', test3: '14', test4: '22'}, {test1: '4', test2: '1', test3: '45', test4: '2'}, {test1: '5', test2: '16', test3: '7', test4: '0'}]

console .log (restructure (input))
.as-console-wrapper {min-height: 100% !important; top: 0}

我们只是从第一个对象中提取共享密钥,并使用它来确定从每个对象中提取什么。

【讨论】:

  • 非常好的解决方案!
  • 很棒的解决方案!
  • 解决方案是单线的,这令人震惊,谢谢!
【解决方案2】:

let input = [{
    test1: '10',
    test2: '15',
    test3: '14',
    test4: '22'
  },
  {
    test1: '4',
    test2: '1',
    test3: '45',
    test4: '2'
  },
  {
    test1: '5',
    test2: '16',
    test3: '7',
    test4: '0'
  }
]

// initialize result array
let result = [...Array(Object.keys(input[0] || {}).length)].map(x => []);
// fill object
input.forEach(val => {
  // push each value into the according position in the result array.
  Object.values(val).forEach((val, i) => {
    result[i].push(val)
  });
});
console.log(result);

【讨论】:

    【解决方案3】:

    有趣。但我不会采用这种方法,我宁愿使用更少的“东西”,就像这样。 我不明白为什么函数被命名为“排序”,没有排序!

    "use strict";
    
    function sort(data)
    {
      var stacks, stacknames;
    
      stacks = [];
      stacknames = {};
    
      data.forEach(item => {
        var k;
    
        for (k in item)
        {
          if (!(k in stacknames))
          {
            stacknames[k] = stacks.length; // map name to index
            stacks.push([]); // allocate new stack
          }
    
          stacks[stacknames[k]].push(parseFloat(item[k]));
        }
      });
    
      return stacks;
    }
    
    var input = [
        {
           test1: '10',
           test2: '15',
           test3: '14',
           test4: '22'
        },
        {
           test1: '4',
           test2: '1',
           test3: '45',
           test4: '2'
        },
        {
           test1: '5',
           test2: '16',
           test3: '7',
           test4: '0'
        }
    ];
    
    var output = sort(input);
    
    console.log(output);

    【讨论】:

      【解决方案4】:

      如果我们使用reduce,那就简单多了。

      var input=[ { test1: '10', test2: '15', test3: '14', test4: '22' }, { test1: '4', test2: '1', test3: '45', test4: '2' }, { test1: '5', test2: '16', test3: '7', test4: '0' }];
      
      var result = Object.values(input.reduce((acc, elem)=>{
        Object.entries(elem).forEach(([k,v])=>{
          acc[k] = acc[k] || [];
          acc[k].push(v);
        })
        return acc;
      },{}));
      
      console.log(result)

      【讨论】:

        【解决方案5】:

        使用嵌套循环可以获得如下预期结果。

        let input = [
            {
               test1: '10',
               test2: '15',
               test3: '14',
               test4: '22'
            },
            {
               test1: '4',
               test2: '1',
               test3: '45',
               test4: '2'
            },
            {
               test1: '5',
               test2: '16',
               test3: '7',
               test4: '0'
            }
        ];
        
        const getValues = (data) => {
          // Get keys in the object
          let keys = Object.keys(data[0]);
          // Initialize the result with empty arrays
          let temp = [...Array(Object.keys(data[0] || {}).length)].map(x => []);
        
          for (let i=0; i<data.length; i++) {
            for (let j=0; j<keys.length; j++) {
              let str = keys[j];
              temp[j].push(data[i][str]);
            }
         }
         console.log(temp);
        }
        
        getValues(input);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-11-25
          • 2017-07-03
          • 1970-01-01
          • 1970-01-01
          • 2012-11-06
          • 2016-10-23
          • 2018-08-07
          相关资源
          最近更新 更多