将列(对象的对象)转换为行(对象的数组)

huangapple go评论68阅读模式
英文:

Convert column (object of objects) into a row (array of objects)

问题

以下是您提供的代码部分的翻译:

我有一个对象其格式如下其中`name``age``gender`是列名而分配给它们的对象是该列的值

{
   'name': {
      0: 'Alpha',
      1: 'Beta',
      2: 'Gamma'
   },
   'age': {
      0: 21,
      1: 25,
      2: 30
   },
   'gender': {
      0: 'Male',
      1: 'Female',
      2: 'Male'
   }
}

我希望将上述对象转换为对象数组

期望输出

[{
   name: 'Alpha',
   age: 21,
   gender: 'Male'
}, {
   name: 'Beta',
   age: 25,
   gender: 'Female'
}, {
   name: 'Gamma',
   age: 30,
   gender: 'Male'
}]

我尝试过什么

我尝试使用[`Object.keys()`][1]首先创建具有键的初始对象`{name: '', age: '', gender: ''}`然后尝试使用[`Object.values()`][2]方法来迭代每个键的值以便动态绑定对象的每个索引值但未能实现

```javascript
const obj = {
   'name': {
      0: 'Alpha',
      1: 'Beta',
      2: 'Gamma'
   },
   'age': {
      0: 21,
      1: 25,
      2: 30
   },
   'gender': {
      0: 'Male',
      1: 'Female',
      2: 'Male'
   };

const columnNameObj = {}
const arr = []
Object.keys(obj).forEach(column => {
   Object.values(obj[column]).forEach((item, index) => {
      columnNameObj[column] = obj[column][index] // <-- 这里我犯了一个错误,因为它迭代了整个循环,最后一个值被分配给对象属性。应该在每次迭代时将对象推送而不是结束内部循环,但我卡在这里了。
})
arr.push(columnNameObj);
})

console.log(arr);

<details>
<summary>英文:</summary>
I am having an object in the below format where `name`, `age` and `gender` are the column names and the object assigned to them are values of that column.
{
&#39;name&#39;: {
0: &#39;Alpha&#39;,
1: &#39;Beta&#39;,
2: &#39;Gamma&#39;
},
&#39;age&#39;: {
0: 21,
1: 25,
2: 30
},
&#39;gender&#39;: {
0: &#39;Male&#39;,
1: &#39;Female&#39;,
2: &#39;Male&#39;
}
}
I want to convert above object into an array of objects.
Expected output **:**
[{
name: &#39;Alpha&#39;,
age: 21,
gender: &#39;Male&#39;
}, {
name: &#39;Beta&#39;,
age: 25,
gender: &#39;Female&#39;
}, {
name: &#39;Gamma&#39;,
age: 30,
gender: &#39;Male&#39;
}]
What I tried so far **?**
I tried with [`Object.keys()`][1] to create the initial object with the keys first `{name: &#39;&#39;, age: &#39;&#39;, gender: &#39;&#39;}` and then tried to iterate over the values of each key with the help of [`Object.values()`][2] method to bind the each index values dynamically against each key of the object but not able to achieve.
&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;
&lt;!-- language: lang-js --&gt;
const obj = {
&#39;name&#39;: {
0: &#39;Alpha&#39;,
1: &#39;Beta&#39;,
2: &#39;Gamma&#39;
},
&#39;age&#39;: {
0: 21,
1: 25,
2: 30
},
&#39;gender&#39;: {
0: &#39;Male&#39;,
1: &#39;Female&#39;,
2: &#39;Male&#39;
}
};
const columnNameObj = {}
const arr = []
Object.keys(obj).forEach(column =&gt; {
Object.values(obj[column]).forEach((item, index) =&gt; {
columnNameObj[column] = obj[column][index] // &lt;-- Here I am doing a mistake as it iterates the whole loop and the last value get assigned to the object property. Object should be pushed on each iteration instead of ending the inner loop but somehow I am stuck here.
})
arr.push(columnNameObj);
})
console.log(arr);
&lt;!-- end snippet --&gt;
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
</details>
# 答案1
**得分**: 2
以下是您要翻译的内容:
"Since your nested values are indexed with sequential integers, you can use these keys to access the relevant index in the result array within a nested loop. Here using [nullish coallescing assignment (??=)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment) to initialize each result object if it doesn't already exist.
```javascript
const input = { name: { 0: 'Alpha', 1: 'Beta', 2: 'Gamma', }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: 'Male', 1: 'Female', 2: 'Male', }, };
const result = [];
for (const [key, values] of Object.entries(input)) {
for (const [index, value] of Object.entries(values)) {
(result[index] ??= {})[key] = value;
}
}
console.log(result);

Or using the same logic in a reduce() call with a nested forEach() if you prefer.

const input = { name: { 0: 'Alpha', 1: 'Beta', 2: 'Gamma', }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: 'Male', 1: 'Female', 2: 'Male', }, };

const result = Object.entries(input).reduce((a, [key, values]) => {
  Object.entries(values).forEach(([index, value]) => {
    (a[index] ??= {})[key] = value;
  });
  return a;
}, []);

console.log(result);
"


<details>
<summary>英文:</summary>

Since your nested values are indexed with sequential integers, you can use these keys to access the relevant index in the result array within a nested loop.
Here using [nullish coallescing assignment (??=)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment) to initialize each result object if it doesn&#39;t already exist.

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    const input = { name: { 0: &#39;Alpha&#39;, 1: &#39;Beta&#39;, 2: &#39;Gamma&#39;, }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: &#39;Male&#39;, 1: &#39;Female&#39;, 2: &#39;Male&#39;, }, };

    const result = [];

    for (const [key, values] of Object.entries(input)) {
      for (const [index, value] of Object.entries(values)) {
        (result[index] ??= {})[key] = value;
      }
    }

    console.log(result);

&lt;!-- end snippet --&gt;

Or using the same logic in a [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) call with a nested `forEach()` if you prefer.

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    const input = { name: { 0: &#39;Alpha&#39;, 1: &#39;Beta&#39;, 2: &#39;Gamma&#39;, }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: &#39;Male&#39;, 1: &#39;Female&#39;, 2: &#39;Male&#39;, }, };

    const result = Object.entries(input).reduce((a, [key, values]) =&gt; {
      Object.entries(values).forEach(([index, value]) =&gt; {
        (a[index] ??= {})[key] = value;
      });
      return a;
    }, []);

    console.log(result);


&lt;!-- end snippet --&gt;



</details>



# 答案2
**得分**: 0

你可以尝试使用数组的reduce方法

```javascript
const data = {
  'name': {
    0: 'Alpha',
    1: 'Beta',
    2: 'Gamma'
  },
  'age': {
    0: 21,
    1: 25,
    2: 30
  },
  'gender': {
    0: 'Male',
    1: 'Female',
    2: 'Male'
  }
}
const dataKeys = Object.keys(data);
const vals = Object.values(data).reduce((acc, curr) => {
  let obj = {};
  // key will be 0,1,2, this is used to get the value from the index
  for (let key in curr) {
    obj[dataKeys[key]] = curr[key]
  }
  acc.push(obj)

  return acc;
}, []);
console.log(vals)
英文:

You can try array reduce

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = {
&#39;name&#39;: {
0: &#39;Alpha&#39;,
1: &#39;Beta&#39;,
2: &#39;Gamma&#39;
},
&#39;age&#39;: {
0: 21,
1: 25,
2: 30
},
&#39;gender&#39;: {
0: &#39;Male&#39;,
1: &#39;Female&#39;,
2: &#39;Male&#39;
}
}
const dataKeys = Object.keys(data);
const vals = Object.values(data).reduce((acc, curr) =&gt; {
let obj = {};
// key will be 0,1,2, this is used to get the value from the index
for (let key in curr) {
obj[dataKeys[key]] = curr[key]
}
acc.push(obj)
return acc;
}, []);
console.log(vals)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月21日 00:52:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定