使用包含多个对象的单个索引遍历数组

 收藏

我有一些看起来像这样的数据

let arr = [
  {
    a:1,
    b:2,
    c:3
  },
  {
    a:4,
    b:5,
    c:6
  },
  {
    a:7,
    b:8,
    c:9
  }
]

我想像这样重新格式化

{
   a: [1,4,7],
   b: [2,5,8],
   c: [3,6,9]
}

Here is my solution to the problem, but I know that this is not the most efficient method. While I completed the exercise, I am having trouble understanding the concepts below:

  • At first glance, arr to me seems like an array with a single index containing three objects. For example, arr[0] = {obj1},{obj2},{obj3}, but I performed a typeof check on arr and it returned object.
  • When I console log arr at a specified index arr[1], it prints out {a:4,b:5,c:6} as if it is an array.
  • My question is what is happening here and what exactly is this type of data structure?

请为我提供一个更干净有效的代码来解决这个问题,并向我解释这些概念。

回复
  • You may use reduce() method for this like:

    let arr=[{a:1,b:2,c:3},{a:4,b:5,c:6},{a:7,b:8,c:9}];
    const res = arr.reduce((r, o) => {
      Object.keys(o).forEach((k) => {
        r[k] = r[k] || [];
        r[k].push(o[k])
      });
      return r;
    }, {})
    
    console.log(res)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

  • ased 回复

    尝试

    function practice (arr) {
      let resultObj = {};
    
      arr.forEach((x) => {
        for (let key in x) {
          if (resultObj.hasOwnProperty(key)) {
            resultObj[key].push(x[key]);
          } else {
            resultObj[key] = [x[key]];
          }
        }
      });
    
      return resultObj;
    }
    

  • In order to check for an array, you should make use of Array.isArray() method. typeof will give you an object since Array is essentially a form of object in javascript created using the Object constructor.

    要获得所需的输出,您需要做的就是遍历数组并将值存储在对象中

    let arr = [
      {
        a:1,
        b:2,
        c:3
      },
      {
        a:4,
        b:5,
        c:6
      },
      {
        a:7,
        b:8,
        c:9
      }
    ]
    
    var res = {};
    arr.forEach((obj) => {
       Object.entries(obj).forEach(([key, val]) => {
          if(res[key]) {
             res[key].push(val);
          } else {
             res[key] = [val];
          }
       })
    });
    
    console.log(res);