[英]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.