Sadu
Sadu

Reputation: 123

How to print jquery object/array

I get id and category name from mysql database.

When I am alerting a result, I get:

[{"id":"197","category":"Damskie"},"id":"198","category":"M\u0119skie"}]

(Is this object?)

  1. How can I print a result like this:

    Damskie

    M\u0119skie

  2. M\u0119ski - has bad encoding. It should be Męskie. How can I change this?

Upvotes: 10

Views: 153360

Answers (5)

Tanvir Rajeev
Tanvir Rajeev

Reputation: 13

I was having similar problem and

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Męskie

This solved my problem. Thanks Selvakumar Arumugam

Upvotes: 0

Parth Raval
Parth Raval

Reputation: 4413

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
var data = arrofobject.map(arrofobject => arrofobject);
console.log(data)

for more details please look at jQuery.map()

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

What you have from the server is a string like below:

var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';

Then you can use JSON.parse function to change it to an object. Then you access the category like below:

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Męskie

Upvotes: 8

Kevin B
Kevin B

Reputation: 95030

Your result is currently in string format, you need to parse it as json.

var obj = $.parseJSON(result);
alert(obj[0].category);

Additionally, if you set the dataType of the ajax call you are making to json, you can skip the $.parseJSON() step.

Upvotes: 4

thecodeparadox
thecodeparadox

Reputation: 87073

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

Upvotes: 33

Related Questions