[英]How to push in array and use Id as index of object
This is the result I want to achieve这是我想要达到的结果
11:{amount:736
wrk_pay_id:11},
10:{amount:714.29
wrk_pay_id:10},
14:{amount:500
wrk_pay_id:14},
13:{amount:857.14
wrk_pay_id:13},
20:{amount:777
wrk_pay_id:20}
this the result of DeductionArray.. I want to change 0,1,2,3,4
indexes to 11,10,14,13,20
这是 DeductionArray 的结果。我想将
0,1,2,3,4
索引更改为11,10,14,13,20
0:{amount:736
wrk_pay_id:11},
1:{amount:714.29
wrk_pay_id:10},
2:{amount:500
wrk_pay_id:14},
3:{amount:857.14
wrk_pay_id:13},
4:{amount:777
wrk_pay_id:20}
This how I push it on my DeductionArray.. this.generated salary
Have 4 object
and the deduction
is on nested array so that I use 2 foreach
to get the value in deduction
这就是我如何将它推到我的 DeductionArray 上
this.generated salary
有4 object
并且deduction
是在嵌套数组上所以我使用2 foreach
来获得deduction
值
const arr = Object.entries(this.generated_salary)
arr.forEach(([key, value]) => {
Object.entries(value.deduction).forEach(([acc, item]) => {
this.DeductionArray.push({
amount: item.amount,
wrk_pay_id: item.wrk_pay_id
})
This.generated_salay这.generated_salay
[
{
"f_name": "Cy",
"deduction": {
"11": {
"amount": 736,
"wrk_pay_id": 11
}
}
},
{
"f_name": "Hel",
"deduction": {
"10": {
"amount": 714.29,
"wrk_pay_id": 10
},
"14": {
"amount": 500,
"wrk_pay_id": 14
}
}
},
{
"f_name": "edd",
"deduction": {
"13": {
"amount": 857.14,
"wrk_pay_id": 13
}
}
},
{
"f_name": "JAY",
"deduction": {
"20": {
"amount": 777,
"wrk_pay_id": 20
}
}
}
]
I'm still guessing due to your question formatting but it looks like you really just want to combine the various deduction
objects into a single object. I don't think an array is a good choice if you're relying on the indexes as keys.由于您的问题格式,我仍在猜测,但看起来您真的只是想将各种
deduction
对象组合成一个 object。如果您依赖索引作为键,我认为数组不是一个好的选择.
// ignore this line, this is just your existing data minified for the demo const generated_salary = [{"f_name":"Cy","deduction":{"11":{"amount":736,"wrk_pay_id":11}}},{"f_name":"Hel","deduction":{"10":{"amount":714.29,"wrk_pay_id":10},"14":{"amount":500,"wrk_pay_id":14}}},{"f_name":"edd","deduction":{"13":{"amount":857.14,"wrk_pay_id":13}}},{"f_name":"JAY","deduction":{"20":{"amount":777,"wrk_pay_id":20}}}] const deductions = generated_salary.reduce((c, { deduction }) => ({...c, ...deduction }), {}) console.info("deductions =", deductions)
.as-console-wrapper { max-height: 100%;important; }
This builds a new object by iterating each entry in generated_salary
and collecting each deduction
object by merging it into the collection as it finds them.这通过迭代
generated_salary
中的每个条目并通过在找到它们时将其合并到集合中来收集每个deduction
object 来构建一个新的 object。
See also Array.prototype.reduce()
and Spread Syntax ( ...
)另见
Array.prototype.reduce()
和Spread Syntax ( ...
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.