简体   繁体   中英

How can I access to each field of a json object?

I have used csvtojson in order to write the csv data into a sql database, the object that the funcion return to have this structure:

var prueba = [
  {'Aula;Capacidad': 'A10+11;112'},
  {'Aula;Capacidad': 'A12;66' }
];

How can I acces to each field? I am trying to do console.log(prueba[0]["Capacidad"]) in order to see if it is running but it prints "undefined".

'Aula;Capacidad' is seen as a key, so you only can do the following:

console.log(prueba[0]["Aula;Capacidad])

which will write

A10+11;112

to the console.

Your properties are actually named 'Aula;Capacidad', meaning you'd need to use prueba[0]['Aula;Capacidad'] to get the value you are looking for.

This is what you need to iterate through the list of items:

var prueba = [{'Aula;Capacidad': 'A10+11;112'},{'Aula;Capacidad': 'A12;66' }]; 
for (var i = 0; i < prueba.length; i++) {
    console.log(prueba[i]);
}

If you need to go deeper and iterate over every item properties:

var prueba = [{'Aula;Capacidad': 'A10+11;112'},{'Aula;Capacidad': 'A12;66' }]; 
for(var i = 0; i < prueba.length; i++) {
    for(var p in prueba[0]) {
        console.log(p, prueba[i][p]);
    }
}

Your data looks malformed so you might need to do some manual processing.

You have an array of two items, both with a single key-value in them. You can do console.log(prueba[0]["Aula;Capacidad"]) and this will return 'A10+11;112' .

You might need to split things by the ; there so you could do something like this:

 var prueba = [ {'Aula;Capacidad': 'A10+11;112'}, {'Aula;Capacidad': 'A12;66' } ]; prueba.forEach(item => { const splitItem = item["Aula;Capacidad"].split(";"); console.log("Each item now looks like this: " + splitItem) // You can access the first and second part of the item like this console.log(splitItem[0], splitItem[1]) })

To be honest, I'd go back and look at how this data is being added to your DB. It looks messed up.

Your key you are looking up is in a composite key. So you would need to look it up with that composite key and than split it.

 var prueba = [ {'Aula;Capacidad': 'A10+11;112'}, {'Aula;Capacidad': 'A12;66' } ]; console.log(prueba[0]['Aula;Capacidad'].split(";")[1]);

Other choice is to parse it all and look it up by the key.

 var prueba = [ {'Aula;Capacidad': 'A10+11;112'}, {'Aula;Capacidad': 'A12;66' } ]; const parsed = prueba.reduce(function (arr, row) { const entry = Object.entries(row)[0]; const keys = entry[0].split(";"); const values = entry[1].split(";"); const data = keys.reduce(function (o, key, index) { o[key] = values[index]; return o; }, {}); arr.push(data); return arr; }, []); console.log(parsed[0].Capacidad); console.log(parsed[1].Capacidad);

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