[英]Extract data from Array on object in java script
我有如下的 JSON 數據:我想為相同的 id 添加 titleaccessed、numberoflogin
[ { id: '1651791',
institutionname: null,
fullname: 'Simi Abraham',
username: ' ',
totalrows: '46',
numberoflogin: '1',
logintimes: 1618963200,
titleaccessed: '2' },
{ id: '1651791',
institutionname: null,
fullname: 'Simi Abraham',
username: ' ',
totalrows: '46',
numberoflogin: '8',
logintimes: 1619049600,
titleaccessed: '18' }]
The expected output is below
[ { id: '1651791',
institutionname: null,
fullname: 'Simi Abraham',
username: ' ',
totalrows: '46',
numberoflogin: '9',// addition of numberoflogin
logintimes: 1618963200,
titleaccessed: '20' // addition of titleaccessed
}]
因為數據需要按 ID 分組,所以可以使用find
或filter
來獲取具有相同 ID 值的條目。 但是,列表越長,速度就會越慢。
或者,可以使用 ID 作為對象的鍵,然后在最后使用Object.values(myObj)
來獲得所需的格式:
const data = [{id: '1651791',institutionname: null,fullname: 'Simi Abraham',username: ' ',totalrows: '46',numberoflogin: '1',logintimes: 1618963200,titleaccessed: '2'},{id: '1651791',institutionname: null,fullname: 'Simi Abraham',username: ' ',totalrows: '46',numberoflogin: '8',logintimes: 1619049600,titleaccessed: '18'}]; const out = Object.values( // format the output as required data.reduce((acc, entry) => { // reduce to a single entry const accEntry = acc[entry.id]; if (accEntry) { // if an entry exists (based on id) accEntry.numberoflogin = (parseInt(accEntry.numberoflogin) + parseInt(entry.numberoflogin)).toString(); // increment login count accEntry.titleaccessed = (parseInt(accEntry.titleaccessed) + parseInt(entry.titleaccessed)).toString(); // increment title access count } else acc[entry.id] = {...entry}; // else create entry return acc; // keep object for next iteration }, {}) // starting with an empty object ); console.log(out, data);
隨着大量條目,這將大大相比更快地運行find
或filter
的方法。
那么你可以簡單地使用reduce()方法來做到這一點。
像這樣的東西
let arrayVal =[ { id: '1651791',
institutionname: null,
fullname: 'Simi Abraham',
username: ' ',
totalrows: '46',
numberoflogin: 1,
logintimes: 1618963200,
titleaccessed: 2 },
{ id: '1651791',
institutionname: null,
fullname: 'Simi Abraham',
username: ' ',
totalrows: '46',
numberoflogin: 8,
logintimes: 1619049600,
titleaccessed: 18 },{ id: '1651792',
institutionname: null,
fullname: 'Simi Abraham',
username: ' ',
totalrows: '46',
numberoflogin: 8,
logintimes: 1619049600,
titleaccessed: 18 }]
let result = arrayVal.reduce((a, c) => {
let filtered = a.filter(el => el.id === c.id);
if(filtered.length > 0){
a[a.indexOf(filtered[0])].titleaccessed += +c.titleaccessed ;
a[a.indexOf(filtered[0])].numberoflogin += +c.numberoflogin;
}else{
a.push(c);
}
return a;
}, []);
console.log(result);
我建議您確保 numberoflogin 和 titleaccessed 的值必須是整數,否則您必須使用 parseInt() 方法手動轉換它,然后添加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.