Hi all,
Im really struggling with this problem today. So basically, I have an array in the format
arr = [{title: " some title", id: "some id"}, {title: " some title2", id: "some id2"}] and all im trying to do is loop through each item in the array and get the value of the ids.
Here is what ive tried:
for( var i = 0; i< arr.length; i++){
console.log(arr[i].id)
}
It keeps showing up as undefined, please can anyone assist me? I would like the result to be "some id"
iterating through object - javascript
java - How to iterate over a JSONObject? - Stack Overflow
How to iterate over a nested JSON object
How do I iterate over a JSON structure?
Videos
You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.
{
"dialog":
{
"trunks":[
{
"trunk_id" : "1",
"message": "This is just a JSON Test"
},
{
"trunk_id" : "2",
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
]
}
}
At that point, I was able to do a fairly simple for loop based on the total number of objects.
var totalMessages = Object.keys(messages.dialog.trunks).length;
for ( var i = 0; i < totalMessages; i++)
{
console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
}
My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.
Maybe this will help:
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
for my case i found iterating the names() works well
for(int i = 0; i<jobject.names().length(); i++){
Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
note: the for-in method is cool for simple objects. Not very smart to use with DOM object.
Taken from jQuery docs:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
The names are a little confusing because of O and 0 ! But you are almost there, here is the fixed code which at least parses your sample json data correctly:
public class MyModel
{
public Outputdata Outputdata { get; set; }
}
public class Outputdata
{
public TASK_0 TASK_0 { get; set; }
public string ERROR_O { get; set; }
}
public class TASK_0
{
public List TASK_O_ITEM { get; set; }
}
public class TASK_O_ITEM
{
public string CODE { get; set; }
public string TASK_NAME { get; set; }
}
And the usage:
var responseBody = "the body from wherever you read";
var result = JsonConvert.DeserializeObject(responseBody);
foreach (var item in result?.Outputdata?.TASK_0?.TASK_O_ITEM)
Console.WriteLine($"{item.CODE} - {item.TASK_NAME}");
Hi @Paul
My thoughts are:
- Declare classes and lists.
- Assign a value to the data.
- Generate JSON variables.
- Print it out
For demonstration purposes, I printed the JSON data as string data.
In order to keep the same format as JSON, I set an option.
var options = new JsonSerializerOptions { WriteIndented = true };
string jsonString = System.Text.Json.JsonSerializer.Serialize(outputdata, options);
Of course, you can also print it directly.
You can refer to the following code:
public class TASK_O
{
public List TASK_O_ITEM { get; set; }
}
public class Outputdata
{
public TASK_O TASK_O { get; set; }
public string ERROR_O { get; set; }
}
public class Example
{
public Outputdata Outputdata { get; set; }
}
public class TASK_O_ITEM
{
public string CODE { get; set; }
public string NAME { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
var task_o_item = new List {
new TASK_O_ITEM
{
CODE = "123",
NAME = "ABC"
},
new TASK_O_ITEM
{
CODE = "456",
NAME = "DEF"
},
new TASK_O_ITEM
{
CODE = "789",
NAME = "GHI"
},
};
var task_O = new TASK_O
{
TASK_O_ITEM = task_o_item
};
var outputdata = new Outputdata
{
TASK_O = task_O,
ERROR_O = null
};
var example = new Example
{
Outputdata=outputdata
};
var options = new JsonSerializerOptions { WriteIndented = true };
string jsonString = JsonSerializer.Serialize(example, options);
Console.WriteLine(jsonString);
Console.Read();
}
}
Result:
Best Regards
Qi You
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.