5 回答
TA贡献1783条经验 获得超4个赞
您可能想按键对值进行分组
使用forEach循环遍历每个项目
input
在每个项目中尝试收集属于该项目的所有键的名称
使用
for...loop
每个键的名称并检查是否obj[k]
为空,然后我们必须分配一个空数组并将此 key( ) 的值推k
入obj[k]
。
这就是解决方案
const input = [
{text1: 'John', text2: 'male'},
{text1: 'Philip', text2: 'male'},
{text1: 'Matthew', text2: 'male'},
{text1: 'Richard', text2: 'male'},
];
function toKeyArray(array) {
const obj = {};
array.forEach(item => {
const keys = Object.keys(item);
for (const k of keys) {
(obj[k] = obj[k] || []).push(item[k]);
}
});
return obj;
}
const output = toKeyArray(input);
console.log(output);
TA贡献1808条经验 获得超4个赞
我们可以使用Array.reduce和实现这一点Object.entries
const obj = [{text1:"John",text2:"male"},{text1:"Philip",text2:"male"},{text1:"Matthew",text2:"male"},{text1:"Richard",text2:"male"},]
const formatData = (data) => data.reduce((res, obj) => {
Object.entries(obj).forEach(([key, val]) => {
res[key] = [...(res[key] || []), val];
});
return res;
}, {});
console.log(formatData(obj));
.as-console-wrapper {
max-height: 100% !important;
}
TA贡献2019条经验 获得超9个赞
const input = [
{ text1: "John", text2: "male" },
{ text1: "Philip", text2: "male" },
{ text1: "Matthew", text2: "male" },
{ text1: "Richard", text2: "male" },
];
const output = {
text1: input.map( e => e.text1 ),
text2: input.map( e => e.text2 )
};
TA贡献1818条经验 获得超7个赞
const obj = [{
text1: "John",
text2: "male"
},
{
text1: "Philip",
text2: "male"
},
{
text1: "Matthew",
text2: "male"
},
{
text1: "Richard",
text2: "male"
},
];
var output = {}
obj.forEach(item => {
Object.keys(item).forEach(key => {
if (!output[key]) output[key] = [];
output[key].push(item[key])
})
})
console.log(output);
TA贡献1735条经验 获得超5个赞
使用Array.prototype.reduce,这可以简单地完成。
const obj = [
{ text1: "John", text2: "male" },
{ text1: "Philip", text2: "male" },
{ text1: "Matthew", text2: "male" },
{ text1: "Richard", text2: "male" },
];
const output = obj.reduce((acc, cur) => {
Object.keys(cur).forEach((item) => {
acc[item] ? acc[item].push(cur[item]) : acc[item] = [ cur[item] ];
});
return acc;
}, {});
console.log(output);
添加回答
举报