我有一個像
const dd = [{
keyone: "test",
two: "you",
three: 'op',
}, {
keyone: "youuuu",
two: "ttt",
three: 'op',
}, {
keyone: "operation",
two: "test",
three: 'op',
}];
我希望能夠將 keyone 和兩個拉出到如下物件中
const obj = { keyone: ['test', 'youuuu', 'operation'], two: ['you', 'ttt', 'test']}
我已經使用兩張地圖并將它們組合起來實作了這一點,但如果可能的話,我只想使用一個回圈。
編輯:
我目前正在使用解構來提取值:
const mapOne = dd.map(({ keyone }) => keyone);
const mapTwo = dd.map(({ two }) => two);
const test = {
keyone: mapOne,
two: mapTwo,
};
uj5u.com熱心網友回復:
一個通用實作,因此可重用和可配置的功能,它完全符合 OP 的要求,將接近下一個提供的示例代碼......
function groupAndCollectSpecifcEntriesOnly(collector, item) {
const { keyList, result } = collector;
keyList.forEach(key => {
if (item.hasOwnProperty(key)) {
(result[key] ??= []).push(item[key])
}
});
return collector;
}
const sampleData = [{
keyone: "test",
two: "you",
three: 'op',
}, {
keyone: "youuuu",
two: "ttt",
three: 'op',
}, {
keyone: "operation",
two: "test",
three: 'op',
}];
console.log(
sampleData.reduce(groupAndCollectSpecifcEntriesOnly, {
keyList: ['keyone', 'two'],
result: {},
}).result
);
console.log(
sampleData.reduce(groupAndCollectSpecifcEntriesOnly, {
keyList: ['three', 'keyone'],
result: {},
}).result
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
uj5u.com熱心網友回復:
您可以獲取一組鍵并將值組合在一起。
const
data = [{ keyone: "test", two: "you", three: 'op' }, { keyone: "youuuu", two: "ttt", three: 'op' }, { keyone: "operation", two: "test", three: 'op' }],
keys = ['keyone', 'two'],
grouped = data.reduce((r, o) => {
keys.forEach(k => (r[k] ??= []).push(o[k]));
return r;
}, {});
console.log(grouped);
uj5u.com熱心網友回復:
你可以這樣做:
const dd = [
{
keyone: "test",
two: "you",
three: 'op'
},
{
keyone: "youuuu",
two: "ttt",
three: 'op'
},
{
keyone: "operation",
two: "test",
three: 'op'
}];
const result = dd.reduce((prev, acc, arr ) => {
if (acc['keyone']) { prev['keyone'].push(acc['keyone']) }
if (acc['two']) { prev['two'].push(acc['two']) }
return prev;
}, {keyone: [], two: []});
console.log(result);
uj5u.com熱心網友回復:
您可以使用reduce對陣列進行一次迭代,并在每次迭代中通過Object.keys和forEach迭代物件:
const data = [ { keyone: "test", two: "you", three: 'op' }, { keyone: "youuuu", two: "ttt", three: 'op' }, { keyone: "operation", two: "test", three: 'op' }];
const targetKeys = ['keyone', 'two']
const result = data.reduce((acc, obj)=> {
targetKeys.forEach(k => { (acc[k] = acc[k] || []).push(obj[k]) });
return acc;
}, {});
console.log(result);
uj5u.com熱心網友回復:
我認為這是您正在尋找的答案:(
使用物件解構從每個物件中提取“keyone”和“two”,并將push它們放在同一個map回圈中)
不要忘記檢查未定義。我的代碼假設您不想要零或空字串。
const data =
[{ keyone: "test", two: "you", three: 'op' }, { keyone: "youuuu", two: "ttt", three: 'op' }, { keyone: "operation", two: "test", three: 'op' }];
const test = { keyone:[], two:[] }
data.map(({ keyone, two }) => {
if ( keyone )
test.keyone.push( keyone );
if ( two )
test.two.push( two )
})
console.log( test )
uj5u.com熱心網友回復:
我對 JavaScript 相當陌生,也許我的解決方案不是最好的。我創建了一個函式,您可以在其中添加要從中獲取資訊的鍵的數量作為可選引數。我假設您不知道鍵的名稱。
const dd = [{
keyone: "test",
two: "you",
three: 'op',
}, {
keyone: "youuuu",
two: "ttt",
three: 'op',
}, {
keyone: "operation",
two: "test",
three: 'op',
}];
getterInformation(dd);
function getterInformation(object, keyCount = Object.keys(object).length) {
let objectWithDesiredKey = {};
for (let index = 0; index < keyCount; index ) {
objectWithDesiredKey[`${Object.keys(object[0])[index]}`] = [];
}
object.forEach((items) => {
for (const key in items) {
if (key in objectWithDesiredKey) {
objectWithDesiredKey[key].push(items[key]);
}
}
});
console.log(objectWithDesiredKey);
}
.as-console-wrapper { min-height: 100%!important; top: 0; }
uj5u.com熱心網友回復:
const dd = [{
keyone: "test",
two: "you",
three: 'op'
},
{
keyone: "youuuu",
two: "ttt",
three: 'op'
},
{
keyone: "operation",
two: "test",
three: 'op'
}
];
const pullOut = (...keys) => {
return keys.map(key => {
const val = dd.reduce((pV, cV, cI) => {
pV.push(cV[key]);
return pV;
}, []);
return {
[key]: val
};
}).reduce(((r, c) => Object.assign(r, c)), {});
};
console.log(pullOut('keyone', 'two'));
uj5u.com熱心網友回復:
這是一個函式,它接受一個物件陣列,后跟您希望收集的任意數量的鍵(我使用了rest 引數語法來收集鍵串列。)。這個函式回圈一次你想要收集的鍵的數量,一次回圈物件的數量(O(mn):與reduce相同)。初始化陣列的第三個回圈可以與物件回圈結合使用,但為了便于閱讀,我將其留在那里。(所以它是 O(mn m))
我看不出使用 reduce、forEach 或 map 更具可讀性的任何需要或優勢。
function reduceArrayOfObjectsToArraysOfValues(
arrayOfObjects,
...keys
){
const result = {}
keys.forEach( key => {
result[ key ] = []
})
arrayOfObjects.forEach( obj => {
keys.forEach( key => {
if ( obj.hasOwnProperty( key )) {
result[key].push( obj[key] )
}
})
})
return result
}
const data = [ { keyone: "test", two: "you", three: 'op' }, { keyone: "youuuu", two: "ttt", three: 'op' }, { keyone: "operation", two: "test", three: 'op' }];
console.log( reduceArrayOfObjectsToArraysOfValues( data, 'keyone', 'two' ))
// == { "keyone": [ "test", "youuuu", "operation"],
// "two": [ "you", "ttt", "test" ]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417481.html
標籤:
