我有一个json
数组如下,该数据来自excel表并转换为json
格式。
[{
'booktitle': 'Leading',
'bookid': '56353',
'bookauthor': 'Sir Alex Ferguson'
}, {
'booktitle': 'How Google Works',
'bookid': '73638',
'bookauthor': 'Eric Smith'
}, {
'booktitle': 'The Merchant of Venice',
'bookid': '37364',
'bookauthor': 'William Shakespeare'
}]
我想在一个数组中获取具有相同键的值。该键值对将是动态的,因此需要一个通用的解决方案。
最佳答案
我想你正在寻找的是这个。如果您想添加其他内容,请告诉我。 检查代码片段。
const obj = [{
'booktitle': 'Leading',
'bookid': '56353',
'bookauthor': 'Sir Alex Ferguson'
}, {
'booktitle': 'How Google Works',
'bookid': '73638',
'bookauthor': 'Eric Smith'
}, {
'booktitle': 'The Merchant of Venice',
'bookid': '37364',
'bookauthor': 'William Shakespeare'
}];
const res = obj.reduce((a, b) => {
for(let i in b) {
if(!a[i]) {
a[i] = [];
}
a[i].push(b[i]);
}
return a;
}, {});
console.log(res);
关于javascript - 动态 json 数组使同一个数组具有相同的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880882/