in my company, big data is saved as an excel file and I have converted the data to a JSON file for processing, but it's difficult for a novice like me like this
var Task = [{
id1: 01,
id2: 02,
money: 400
},{
id1: 03,
id2: 02,
money: 200
},{
id1: 01,
id2: 02,
id3: 03,
money: 300
}]
the difficult thing I am facing is how to put them into 1 array of employees, with a corresponding amount, for example, task has 3 ids (id1, id2,id3) then money will divide by 3, a task with 2 ids will divide by 2
what I want
var employee = [{
id: 001,
money: 400
},{
id: 002,
money: 400
},{
id: 003,
money: 100
}]
I tried the below code but it can only apply with 1 unique id as first id
var nv = nhanvien.reduce((acc, cur) => {
var existingnhanvien = nhanvien.find(o => o.id1 === cur.id )
if (existingnhanvien) {
existingnhanvien.money= parseInt(existingnhanvien.money cur.money)
}
else {
acc.push({
id: cur.id1,
money: cur.money
})
}
return acc
}, [])
CodePudding user response:
Iterate your Task
array, and for each object extract keys.
var Task = [{
id1: 01,
id2: 02,
money: 400
}, {
id1: 03,
id2: 02,
money: 200
}, {
id1: 01,
id2: 02,
id3: 03,
money: 300
}, {
id1: 01,
id2: 02,
id3: 03,
id4: 04,
id5: 05,
id6: 06,
money: 300
}]
let obj = {}
for (let t of Task) {
let money = t.money
let keys = Object.keys(t)
// ALL KEYS EXCEPT OF "money"
keys.splice(Object.keys(t).indexOf('money'))
// SPLIT MONEY BETWEEN IDs
let chunk = money / keys.length
for (k of keys) {
if (typeof obj[t[k]] == 'undefined') {
// IF EMPLOYEE DOESN'T EXIST IN OBJECT, INITIALIZE IT
obj[t[k]] = chunk
} else {
// IF EMPLOYEE EXISTS IN OBJECT, INCREMENT ITS VALUE
obj[t[k]] = chunk
}
}
}
let employees = Object.keys(obj).map(key => { return { id: key, money: obj[key] } })
console.log(employees)
CodePudding user response:
var Task = [{
id1: 01,
id2: 02,
money: 400
},{
id1: 03,
id2: 02,
money: 200
},{
id1: 01,
id2: 02,
id3: 03,
money: 300
}];
let employee = [];
for(t of Task) {
let ids = [];
if(t.hasOwnProperty("id1")) {
ids.push(t.id1);
}
if(t.hasOwnProperty("id2")) {
ids.push(t.id2);
}
if(t.hasOwnProperty("id3")) {
ids.push(t.id3);
}
let money = t.money/ids.length;
for(let i of ids) {
let exists = false;
for(let e of employee) {
if(i == e.id) {
exists = true;
e.money = money;
}
}
if(!exists) {
employee.push({id: i, money: money})
}
}
}
console.log(employee);