Use elements from a predefined list as variables on a JavaScript function

Viewed 41

I have a predefined list which is the next one:

let services_list = ["SUCURSALES_BANCA_COMERCIAL", "SUCURSALES_BANCA_DE_DESARROLLO",
"SUCURSALES_SOCAP","SUCURSALES_SOFIPO", "CORRESPONSALES", "CAJEROS_AUTOMÁTICOS",
"TERMINALES_PUNTO_DE_VENTA", "ESTABLECIMIENTOS_CON_TPV"]

And then I have the following function:

let state = document.getElementById("stateDrop").value
let example = []
d3.json("../api_states").then(function(data){
    data.forEach(function(d){
        if(d.ENTIDAD === parseInt(state)){
         services_list.forEach(function(f){
            example.push(d.f)
         })
        }
    })
})

What I want is to enter each element of the predefined list, and use that element as a variable in the example.push part. So the data would contain something like

{"SUCURSALES_BANCA_COMERCIAL":10}

So instead of typing every key I would like to access it with the mentioned list, however the (d.f) part is not recognized.

I hope I make myself clear.

1 Answers

Assuming the variable f is the string and d is the number like

// { f: d } 
{"SUCURSALES_BANCA_COMERCIAL":10}

You can do this in your code

.
.
    data.forEach(function(d){
        if(d.ENTIDAD === parseInt(state)){
         services_list.forEach(function(f){
            const obj = {};
            obj[f] = d;
            example.push(obj);
         })
        }
    })
.
.

so your example array would have elements with key-value pairs

Related