1

I get results from a query where each field is a separate table. For exemple, for this table (ordered by Product, Step) :

PRODUCT | STEP      | WORKER
Car     | Polishing | Carl
Car     | Painting  | Peter
Car     | Painting  | Mark
Bike    | Painting  | Paul
Boat    | Repairing | Alex

I'll have 3 tables (Product, Step, Worker). I'd need to put this in another object ending up like that :

var factory = [
    [
        [{"product":"Car","step":"polishing","workers":[{"name":"Carl"}]}],
        [{"product":"Car","step":"painting","workers":[{"name":"Peter"},{"name":"Mark"}]}]
    ],
    [
        [{"product":"Bike","step":"painting","workers":[{"name":"Paul"}]}]
    ],
    [
        [{"product":"Boat","step":"repairing","workers":[{"name":"Alex"}]}]
    ]
]

I'm using javascript. Could anyone help please ?

Here's what I tried :

var factory = [];
var currentProduct = [];
var currentStep = [];
var currentWorker = {"name":workers[0]};
var currentStepItem = {
    "product":product[0],
    "step":step[0],
    "workers":[currentWorker]
};
currentStep.push(currentStepItem);
currentProduct.push(currentStep);
factory.push(currentProduct);

for(var i = 1 ; i < product.length ; i++){
    if(product[i] == product[i-1]){
        //I'm stuck here
    }
}
Nes
  • 27
  • 5
  • 2
    Does this answer your question? [How to convert HTML table to Javascript Object with jQuery](https://stackoverflow.com/questions/12290927/how-to-convert-html-table-to-javascript-object-with-jquery) – A. El-zahaby May 12 '20 at 08:39
  • have a look at this: https://stackoverflow.com/a/12291010/7511165 – A. El-zahaby May 12 '20 at 08:39
  • Properly state the input. It sounds like you have three *table columns* and you're getting an array of objects? Or how does this query result look, exactly? Sorting them into `factory` based on `product` is simple, I guess combining them if `step` is the same is the hard part? What have you tried so far? Do you know about array methods like forEach() and reduce()? –  May 12 '20 at 08:43
  • I know about forEach(), but never heard of reduce() before, I'll have a look. For what I tried, I'll update my post to insert the code. I'll also look the links and see if this helps, thanks – Nes May 12 '20 at 08:49
  • I updated my post and the title too, converting HTML tables doesn't helps I'm not working with HTML tables here, I got the result from an sql query as 3 arrays. I've looked about reduce(), but I don't really understand how to use it yet, and don't have a clue how to implement it to get my expected result – Nes May 12 '20 at 09:02

1 Answers1

0

ok, wasn't easy, but I found a way : jsfiddle.net/c8edzut5

Nes
  • 27
  • 5