0

This is my json object i want to get alert it without the array order like[0], [1].

  var jsononj = {
    "objnew" : 
    [{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
] }; 

    }

var newtest = jsononj.objnew[0].testarry;
    alert(newtest);

i want to alert without [0]. how to i achieve this

supersaiyan
  • 1,670
  • 5
  • 16
  • 36
  • 2
    What bothers you with the `[0]`? You have an array with 2 elements and you want to show some information from the first element. How do you expect that to happen without telling the system that you want the *first* element? Javascript is not that intelligent enough to be able to read your mind, yet. – Darin Dimitrov Jun 21 '13 at 09:14
  • these order can be rearrange anytime but "key" would remain the same thats the reason – supersaiyan Jun 21 '13 at 09:16
  • Where did you see *a key*? In the example you have shown I can only see a message. You see, that's what happens when you are not telling us everything and showing your real code and real problem. – Darin Dimitrov Jun 21 '13 at 09:16
  • key i mean here is :testarry this would remain the same – supersaiyan Jun 21 '13 at 09:18
  • 1
    I think @SachinRawal is looking for a way to iterate trough the json in order to find the array that contains a given key. – cutsoy Jun 21 '13 at 09:19

4 Answers4

1

I think this is what you're looking for:

var i;
for (i = 0; i < jsonobj.objnew.length; i++) {
    if (jsonobj.objnew[i].testarry) {
        alert(jsonobj.objnew[i].testarry);
    }
}
cutsoy
  • 10,127
  • 4
  • 40
  • 57
0

doing a var firstOne = jsononj.objnew[0];

but if you simply don't like the [0] through your lines, extend the Array prototype

Array.prototype.first = function () {
    return this[0];
};
var newtest = jsononj.objnew.first().testarry;
alert(newtest);

more info at First element in array - jQuery

Community
  • 1
  • 1
Edorka
  • 1,781
  • 12
  • 24
0

This is just stupid but I removed the [0]

var jsononj = {
    "objnew" : [
        {testarry: "thi is my demo text" },
        {testarry2: "thi is my demo text2" }
    ]
};

var a = jsononj.objnew.shift();
alert(a.testarry);
jsononj.objnew.unshift(a);
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

That's not JSON, that's a Javascript object. JSON is a text format for representing data.

If you want to look for an object with a specific property, loop through the objects in the array and check for it:

var newtest = null;
for (var i = 0; i < jsononj.objnew.length; i++) {
  var obj = jsononj.objnew[i];
  if (obj.hasOwnProperty('testarry') {
    newtest = obj.testarry;
    break;
  }
}
if (newtest != null) {
  // found one
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005