简体   繁体   中英

How to convert JSON object with multiple objects into a single set of objects

I have a JSON object with multiple objects which I have to convert into a single object so I can insert it into an mysql table.

I'm doing this on JavaScript, but I have no idea how to convert it into a "row" so I can send it into an insert for mysql

The ID must contain all the anotherIDs with every ConceptID and ConceptValue

ConceptID and ConceptValue must be on each anotherID, so the result would be like the one I show on the example

Example:

JSON
{
  ID: "1"
  AnotherID: "003,004,006,007,008,009,010"
  ConceptID: "A,B,C"
  ConceptValue: "23,45,63"
}

And I want to insert it into a mysql table like this:

ID  |  AnotherID  |  ConceptID  |  ConceptValue
===============================================
1   |  003        |  A          |  23
1   |  003        |  B          |  45
1   |  003        |  C          |  63
1   |  004        |  A          |  23
1   |  004        |  B          |  45
1   |  004        |  C          |  63

I've tried it doing it on an stored procedure in mysql, but couldn't make it work.

I'm kinda new at development, so any help would be really appreciated!

I've tried with a ForEach so I can get the JSON in single parts

var $IDs;
var count = 0;
  JSON_Object.forEach(function (element) {
    count++;
    $IDs.push(element[count].ID.value);
});

But, then I don't know how to order them like the result I want to and generate each row.

I think you have an object like

let obj = {
 ID: "1",
 AnotherID: "003,004,006,007,008,009,010",
 ConceptID: "A,B,C",
 ConceptValue: "23,45,63"
}

So let's create two variables:

let conceptId = obj.ConceptID.split(','); // Convert to array
let conceptValue = obj.ConceptValue.split(',');

Now this will create a array objects containing AnotherId with conceptId

obj.AnotherID.split(',').reduce((arr, id) => {
 arr.push(...conceptId.map((v, i) => ({
    AnotherId: id,
    ConceptID: v,
    ConceptVaue: conceptValue[i]
 })))
 return arr;
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM