Reputation: 1381
I have 2 array of objects (this.so, model) that I'm trying to manipulate to create a new array of objects (this.soModelBOMs).
I used array.filter().map() on both arrays.
However, I'm getting an Array of Array of Objects instead of just an Array of Objects.
this.soModelBOMs = this.so.filter(x => x.lacking > 0).map(so =>
model.filter(x => x.model_no == so.model_no).map(m => ({
production_id: so.production_id,
model_id: m.model_id,
model_no: m.model_no,
process_rev: m.process_rev,
bom_rev: m.bom_rev,
process: m.process.map(p => ({
process_order: p.process_order,
process_name: p.process_name,
process_no: p.process_no,
process_yield: p.process_yield,
bom: p.bom.map(b => ({
alt: b.alt,
bom_item: b.bom_item,
bom_name: b.bom_name,
bom_code: b.bom_code,
bom_qty: b.bom_qty,
bom_stock: b.bom_stock,
bom_yield: b.bom_yield,
bom_req: b.bom_qty * so.lacking
}))
}))
}))
)
I'm getting something like these:
[
[
{
"production_id": 1,
"model_id": 1,
...
}
],
{
"production_id": 2,
"model_id": 2,
...
}
[
{
"production_id": 3,
"model_id": 3,
...
}
],
]
How do I fix my code so that I can sort of just push the objects into the array instead of pushing the arrays of objects into the array?
Something like this:
[
{
"production_id": 1,
"model_id": 1,
...
},
{
"production_id": 2,
"model_id": 2,
...
},
{
"production_id": 3,
"model_id": 3,
...
}
]
Upvotes: 0
Views: 73
Reputation: 431
You could use find
instead of filter
.
this.soModelBOMs = this.so.filter(x => x.lacking > 0).map(so => {
var m = model.find(x => x.model_no == so.model_no);
if(m) {
return {
production_id: so.production_id,
model_id: m.model_id,
model_no: m.model_no,
process_rev: m.process_rev,
bom_rev: m.bom_rev,
process: m.process.map(p => ({
process_order: p.process_order,
process_name: p.process_name,
process_no: p.process_no,
process_yield: p.process_yield,
bom: p.bom.map(b => ({
alt: b.alt,
bom_item: b.bom_item,
bom_name: b.bom_name,
bom_code: b.bom_code,
bom_qty: b.bom_qty,
bom_stock: b.bom_stock,
bom_yield: b.bom_yield,
bom_req: b.bom_qty * so.lacking
}))
}))
};
}
})
I didn't test this code though.
P.S:
You could refactor your code with spread operator
to something like this
this.soModelBOMs = this.so.filter(x => x.lacking > 0).map(so => {
var m = model.find(x => x.model_no == so.model_no);
if (m) {
return {
...so,
...m,
process: m.process.map(p =>
({
...p,
bom: p.bom.map(b =>
({ ...b,
bom_req: b.bom_qty * so.lacking
}))
})),
}
}
});
Upvotes: 1