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
    }
}
5
  • 2
    Does this answer your question? How to convert HTML table to Javascript Object with jQuery Commented May 12, 2020 at 8:39
  • have a look at this: stackoverflow.com/a/12291010/7511165 Commented May 12, 2020 at 8: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()? Commented May 12, 2020 at 8: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 Commented May 12, 2020 at 8: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 Commented May 12, 2020 at 9:02

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.