ReynierPM
ReynierPM

Reputation: 18660

Find key in Javascript object and get values for each one

I am working on this code:

$.post(Routing.generate('vincularFabricanteModeloMarca'), {
    fabricantesMarcaModelo: fabricantesMarcaModelo.serializeArray(),
    paresMarcaModelo: paresMarcaModelo.serializeArray()
}, 'json').done(function (data, textStatus, jqXHR) {
    if (data.success) {
        console.log(data.ent);

        $.each(data.ent, function (k, v) {
            var countries = '';
            var maker = '';

            var makerId = null;
            console.log(v.paisesFabricanteModeloMarca);

            $.each(v.paisesFabricanteModeloMarca, function (l, w) {
                $.each(w, function (x, z) {
                    countries += (countries == '' ? '' : ', ') + z.nombrepais;
                    maker = z.nombrefabricantedistribuidor;
                    makerId = z.idfabricantedistribuidor;
                });

                var btn = '<button data-rel-id="' + makerId + '" class="btn btn-default btn-sm btn-fabricante"><i class="fa fa-close fx"></i> ' + maker + ' (' + countries + ')</button>';
                $('td[data-modelomarcaproductofabricantes="' + v.idModeloMarca + '"]').append(btn);
            });
        });
    }
}).fail(function () { });

How do I get the key value on this Javascript object on this result set in order to find the right td on this line:

$('td[data-modelomarcaproductofabricantes="' + (here) + '"]').append(btn);

(here) should be the key for each loop, how? See the pictures below for a test result set, any advice?

console.log(data.ent)

this is what console.log(data.ent) returns

This is the server side response as a JSON

enter image description here

Upvotes: 1

Views: 455

Answers (2)

ReynierPM
ReynierPM

Reputation: 18660

So after @mido22 suggestion I rewrite my own code and get this:

$.each(data.ent, function (k, v) {
    var countries = '',
        maker = '',
        makerId = null;

    $.each(v, function (l, w) {
        $.each(w.paisesFabricanteModeloMarca, function (i, j) {
            countries += (countries == '' ? '' : ', ') + j.nombrepais;
            maker = j.nombrefabricantedistribuidor;
            makerId = j.idfabricantedistribuidor;
        });

        var btn = '<button data-rel-id="' + makerId + '" class="btn btn-default btn-sm btn-fabricante"><i class="fa fa-close fx"></i> ' + maker + ' (' + countries + ')</button>';
        $('td[data-modelomarcaproductofabricantes="' + l + '"]').append(btn);
    });
});

Fully functional and apparently works for me! Hope this help others. Happy codding!!

Upvotes: 0

mido
mido

Reputation: 25034

looking at your code and JSON, I feel like you are missing a loop,

The JSON structure seems to be Array-->Object-->Object-->Array,
and your loop is like Array-->Object-->Array,

check if this works,

$.each(Object.keys(v), function(k1,v1){  
    console.log(v[v1].paisesFabricanteModeloMarca);
});

Upvotes: 1

Related Questions