-1

I requested some data from my django server. Then I used JSON.parse to deserialized the data into a JSON object.I want to loop through each object field attribute and call the function createDiv on each of them.

  function load_blog(){

  let start_blog = 0
  let end_blog = 4

  fetch(`/blog/?start=${start_blog}&end_blog=${end_blog}`)
  .then(response => response.json())
  .then(json_blogs => {
    var jsblog = JSON.parse(json_blogs)
    jsblog.fields.forEach()

  })
}

This is how my data looks after using JSON.parse enter image description here

I would like to use the function on each field dict.However I'm getting this error:

jsblog.fields is undefined

And I'm clearly seeing fields from the console. So could anyone assist me?

  • Your `jsblog` is an array of four objects, each one containing a property named `fields`, whose value is itself an object. Therefore, `jsblog.fields` is undefined, as expected. What you have to do is iterate over the array (for instance, `jsblog.forEach(o => { doSomethingWith(o.fields); })`, doing whatever you want with each `fields` property inside the loops. – Gerardo Furtado Mar 06 '23 at 06:39
  • Does this answer your question? [How can I access and process nested objects, arrays, or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – gre_gor Mar 06 '23 at 06:48
  • You are already calling `response.json()`. Why are you parsing again with `JSON.parse`? – gre_gor Mar 06 '23 at 06:51
  • I wasn't getting the data in an array of objects before json.parse. – Matthew Manning Mar 06 '23 at 18:56

1 Answers1

0

First things first, if I'm right, jsblog is an array of Objects, right?

Thus if you want to iterate on jsblog, you might want to do that in this way: jsblog.forEach(...). Then in the callback, you can reference fields property of each object.

jsblog.forEach(blogObject => console.log(blogObject.fields));

By jsblog.fields, you tried to access the property called fields of the array of objects, which shall be undefined. jsblog does not have fields property, but the children of jsblog do.

dlguswo333
  • 31
  • 1
  • 3