raducup
raducup

Reputation: 711

How to get first (and only one) element from data.items (getJson funcion)

I can't find how to get the first and only element from data.items, I do not want to use foreach function since I have just one element there.

Upvotes: 0

Views: 7635

Answers (2)

user1979270
user1979270

Reputation:

Try this:

... success: function (data) {
 var oneItem = data[0].items;
 }

Edit:

Here is whole code

$.ajax({
url: "functionURL",
type: "GET/POST",
data: {functionArgument_Name:passingArgument_name},
success: function (data) {
var oneItem = data..;
}
});

So if you have something like this

public JsonResult getOneItem(string name)
{     
 Dictionary<String, String> items= new Dictionary<string, string>();
 items.Add("items",name);
 return Json(items, JsonRequestBehavior.AllowGet);
}

Your ajax should look something like this:

$.ajax({
url: "getOneItem",
type: "POST",
data: {name:"abcde"},
success: function (data) {
var oneItem = data.items;
}
});

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Like this, probably :

var myOneItem = data.items[0];

This will work if

  • your object was already parsed (which should be the case using getJSON as the name doesn't imply)
  • there's an items property
  • this property's value is an array

EDIT : from your comment it seems you need that :

for (var key in data) {
    var val = data[key];
}
// you can use val here

Upvotes: 3

Related Questions