How to regroup 2 JSONs for a given position? I put 2 examples to show what I want

0

I have 2 examples of the select that I want to generate a good one and a bad one. There you will see.

$(document).ready(function() {
  var result_malo = [
    [
      {
        "id": 1,
        "nombre": "Bocina"
      },
      [
        {
          "id": 2,
          "nombre": "Bocina Der"
      	}
      ]
    ],
    [
      {
        "id": 1,
        "nombre": "Bocina"
      },
      [
        {
          "id": 3,
          "nombre": "Bocina Central"
        }
      ]
    ],
    [
      {
        "id": 4,
        "nombre": "Jeringa"
      },
      [
        {
          "id": 4,
          "nombre": "Jeringa Inf"
        }
      ]
    ],
    [
      {
        "id": 4,
        "nombre": "Jeringa"
      },
      [
        {
          "id": 5,
          "nombre": "Jeringa Sup"
        }
      ]
    ],
    [
      {
        "id": 2,
        "nombre": "Mecanica"
      },
      [
        {
          "id": 7,
          "nombre": "Motor Principal"
        }
      ]
    ]
  ];
  $.each(result_malo, function(key, value) {
    $("#crear_subpartes_malo")
      .append('<optgroup label="' + value[0].nombre + '">');
    $("#crear_subpartes_malo")
      .append('<option value="' + value[1][0].id + '">' + value[1][0].nombre + '</option>');
    $("#crear_subpartes_malo").append('</optgroup>');
  });
  var result_bueno = [
    [
      {
        "id": 1,
        "nombre": "Bocina"
      },
      [
        {
          "id": 2,
          "nombre": "Bocina Der"
        },
        {
          "id": 3,
          "nombre": "Bocina Central"
        }
      ]
    ],
    [
      {
        "id": 4,
        "nombre": "Jeringa"
      },
      [
        {
          "id": 4,
          "nombre": "Jeringa Inf"
        },
        {
          "id": 5,
          "nombre": "Jeringa Sup"
        }
      ]
    ],
    [
      {
        "id": 2,
        "nombre": "Mecanica"
      },
      [
        {
          "id": 7,
          "nombre": "Motor Principal"
        }
      ]
    ]
  ];
  $.each(result_bueno, function(key, value) {
    $("#crear_subpartes_bueno")
      .append('<optgroup label="' + value[0].nombre + '">');
    for (i = 0; i < value[1].length; i++) {
      $("#crear_subpartes_bueno")
        .append('<option value="' + value[1][i].id + '">' + value[1][i].nombre + '</option>');
    }
    $("#crear_subpartes_bueno").append('</optgroup>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label for="crear_subpartes_malo">Este es el select cargado con el JSON que obtengo</label>
	<br/>
	<select multiple id="crear_subpartes_malo" name="crear_subpartes_malo" style="width: 150px;height: 200px;"></select>
	<br/>
	<br/>
	<label for="crear_subpartes_malo">Este es el select cargado con un JSON creado por mi</label>
	<br/>
	<select multiple id="crear_subpartes_bueno" name="crear_subpartes_bueno" style="width: 150px;height: 200px;"></select>

Update 1:

JSON: "result_good" this is how I want my JSON to be ordered JSON: "result_malo" but this is what I get from the DB

I would like to order it with javascript or jQuery , from the DB not because there is no way or at least I can not find the way.

Update 2:

I have 4 tables for the query:

computers: id, name
parts: id, name
subparts: id, name, sub_id
sub-teams: id, team_id, sub_id

This last one is a bridge, why do not I relate equipos to partes ? Well, because there are names of subpartes that are repeated in equipos and it is the only way that occurred to me to avoid repetition of nombres in the subpartes table. I do not know if I'm doing it right or if I'm wrong, suggestions are welcome. PS: it's the first time I work a bridge like that.

The query is done with laravel in the following way:

public function getSubpartes(Request $req, $id){
    if($req->ajax()){
        $result = 'select "subpartes"."id", "subpartes"."nombre" from "equipos_subpartes" inner join "subpartes" on "subpartes"."id" = "equipos_subpartes"."id_subpartes" where "equipos_subpartes"."id_equipos" = '.$id;
        $arrayFinal = array();
        for($i=0;$i<count($result);$i++){
            $arrayPartes = array();
            $resultPartes = 'select "partes"."id", "partes"."nombre" from "subpartes" inner join "partes" on "partes"."id" = "subpartes"."id_partes" where "subpartes"."id" = '.current($result[$i]);
            for($j=0;$j<count($resultPartes);$j++){
                array_push($arrayFinal, array($resultPartes[$j] , $result[$i]));
            }
        }
        Debugbar::info($arrayFinal);
        return $arrayFinal;
    }
}
    
asked by Pablo Contreras 16.02.2017 в 15:54
source

2 answers

1

I try to define what you want to do: a list of parts (speakers, syringes, etc.) and below each one its respective subparts.

For a future consultation, I think it would be good to try to formulate with words what you want to do in general, not just the result you want to get ... and show part of your code.

Anyway, I have the doubt about the table of equipment, since nothing appears on equipment in your JSON I have no idea of its function or utility.

What you show in your JSON could easily be obtained with the following design:

a. Creating tables and inserting values

Eye: For reasons of clarity and good programming practice, get used to giving each thing names that when you see them you know what you mean. If you use several tables and in each one you use a column called "name" to store the names of the parties, subparts, etc. then you will have several columns called "name". Apart from that you could easily get confused when creating your SQL, when you have to use three or more tables in a query and you find several columns with the same name, go mess. That is why you will see that in the different tables each column is called name_ [something that identifies].

CREATE TABLE Partes
    ('id_parte' int, 'nombre_parte' varchar(70))
;

INSERT INTO Partes
    ('id_parte', 'nombre_parte')
VALUES
    (1, 'Bocina'),
    (2, 'Jeringa'),
    (3, 'Mecánica')
;


CREATE TABLE Sub_Partes
    ('id_subparte' int, 'nombre_subparte' varchar(70), 'id_parte' int)
;

INSERT INTO Sub_Partes
    ('id_subparte', 'nombre_subparte', 'id_parte')
VALUES
    (1, 'Bocina Der',1),
    (2, 'Bocina Central',1),
    (3, 'Jeringa Inf',2),
    (4, 'Jeringa Sup',2),
    (5, 'Motor Principal',3)
;

b. See

SELECT 
  nombre_parte, GROUP_CONCAT(nombre_subparte SEPARATOR '|') as nombre_subparte
FROM 
  Partes p
LEFT JOIN 
  Sub_Partes sp 
ON p.id_parte=sp.id_parte
GROUP BY p.id_parte
;

c. Result

| nombre_parte |           nombre_subparte |
|--------------|---------------------------|
|       Bocina | Bocina Central|Bocina Der |
|      Jeringa |   Jeringa Inf|Jeringa Sup |
|     Mecánica |           Motor Principal |

As you can see, in the result you have exactly what you need, in this case, without redundant data.

Here's the fiddle: link

d. But ... how do I present that on screen?

That's the least, for example, you can from the result create a JSON array in which the key is column 1 and the value column 2 and through your javascript separate the values of column 2 using the character

Final note
The tables above I thought, trying to get closer to what you want to get. If this is exactly this, you have an auxiliary table left over to join your parts and subparts (that's why there are only two tables). Now, if a subpart can belong to more than one group of parties (for example, that a "right speaker" may belong to the main part "Speaker" and at the same time to the main part "Syringe"), then you would need a third auxiliary table.

Greetings.

    
answered by 17.02.2017 / 02:35
source
0

Regarding the backend, depending on the serializer of laravel (which I do not know) the output of ->toArray() can be nested, or have the structure of an associative array:

[
  0 => objeto,
  1 => objeto
  2 => objeto
]

which means that your results are nested.

In the frontend, you could try the _.flattenDeep method of the lodash library , so you do not reinvent the wheel with a sui generis recursive method.

    
answered by 16.02.2017 в 18:51