英文:
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.
{
'name': {
0: 'Alpha',
1: 'Beta',
2: 'Gamma'
},
'age': {
0: 21,
1: 25,
2: 30
},
'gender': {
0: 'Male',
1: 'Female',
2: 'Male'
}
}
I want to convert above object into an array of objects.
Expected output **:**
[{
name: 'Alpha',
age: 21,
gender: 'Male'
}, {
name: 'Beta',
age: 25,
gender: 'Female'
}, {
name: 'Gamma',
age: 30,
gender: 'Male'
}]
What I tried so far **?**
I tried with [`Object.keys()`][1] to create the initial object with the keys first `{name: '', age: '', gender: ''}` 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.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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] // <-- 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);
<!-- end snippet -->
[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't already exist.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
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.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
</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 = {
'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)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论