5 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可能想按鍵對(duì)值進(jìn)行分組
使用forEach循環(huán)遍歷每個(gè)項(xiàng)目
input
在每個(gè)項(xiàng)目中嘗試收集屬于該項(xiàng)目的所有鍵的名稱
使用
for...loop
每個(gè)鍵的名稱并檢查是否obj[k]
為空,然后我們必須分配一個(gè)空數(shù)組并將此 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貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個(gè)贊
我們可以使用Array.reduce和實(shí)現(xiàn)這一點(diǎn)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貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊
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貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用Array.prototype.reduce,這可以簡(jiǎn)單地完成。
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);
添加回答
舉報(bào)