如何在对象数组中获取 1 到 n 键值并将它们推送到新数组?(Javascript)[重复]
Posted
技术标签:
【中文标题】如何在对象数组中获取 1 到 n 键值并将它们推送到新数组?(Javascript)[重复]【英文标题】:How to get 1 to n key value in an array of objects and push them to a new array?(Javascript) [duplicate] 【发布时间】:2022-01-18 09:15:33 【问题描述】:我有一个对象数组,
[
trial1: 'a1', trial2: 'a2', trial3: 'a3',
trial1: 'b1', trial2: 'b2', trial3: 'b3',
trial1: 'c1', trial2: 'c2', trial3: 'c3',
]
如何获得这样的数组数组
[
['a1','a2','a3'],
['b1','b2','b3'],
['c1','c2','c3']
]
还有这样的数组
[
['a1','b1','c1'],
['a2','b2','c2'],
['a3','b3','c3']
]
【问题讨论】:
别忘了mark one of the answers as accepted。 【参考方案1】:使用.map(Object.values)
:
let data = [
trial1: 'a1', trial2: 'a2', trial3: 'a3',
trial1: 'b1', trial2: 'b2', trial3: 'b3',
trial1: 'c1', trial2: 'c2', trial3: 'c3',
];
let result = data.map(Object.values);
console.log(result);
当你需要转置时:
let data = [
trial1: 'a1', trial2: 'a2', trial3: 'a3',
trial1: 'b1', trial2: 'b2', trial3: 'b3',
trial1: 'c1', trial2: 'c2', trial3: 'c3',
];
let result = data.map(Object.values);
result = result[0].map((_, i) => result.map(row => row[i]));
console.log(result);
【讨论】:
非常感谢。 如何转置这个数组 见Transposing a 2D-array。也添加到我的答案中。【参考方案2】:您可以像这样使用map
和Object.values
来做到这一点:
const data = [
trial1: 'a1', trial2: 'a2', trial3: 'a3',
trial1: 'b1', trial2: 'b2', trial3: 'b3',
trial1: 'c1', trial2: 'c2', trial3: 'c3',
];
const values = data.map(Object.values).map((item,i,self) => self.map(o => o[i]) );
console.log(values)
【讨论】:
非常感谢。我如何转置这个数组? 不客气,我编辑了我的答案以转置它。以上是关于如何在对象数组中获取 1 到 n 键值并将它们推送到新数组?(Javascript)[重复]的主要内容,如果未能解决你的问题,请参考以下文章