-2

I have created array in a object,

var obj_report_dailog = { array_report_dailog : [] }

Then push data to object,

obj_report_dialog.array_report_dialog.push({from: fromDate})
obj_report_dialog.array_report_dialog.push({to: toDate})
obj_report_dialog.array_report_dialog.push({fabrika: fabrika})

Then,

var json = JSON.stringify(obj_report_dialog);

How can I access to elements of that object?

console.log("işte bu: " + json); 

output:

işte bu: {"array_report_dialog":[{"from":"2017-08-01"},{"to":"2017-09-21"},{"fabrika":["Balçova"]}]}
ilvthsgm
  • 586
  • 1
  • 8
  • 26

3 Answers3

3

Two things:

  1. You don't want to JSON.stringify unless you're sending the resulting string somewhere that will parse it. Remember, JSON is a textual notation for data exchange; JSON.stringify gives you a string to send to some receiver. When you have the JSON string, you don't access the properties of the objects in it.

    If you're receiving that JSON string, you'd parse it via JSON.parse and then access the properties on the result.

  2. Leaving aside the JSON thing, you probably don't want to add data the way you're adding it. You're adding three separate objects as three entries in the array, each with one property. You probably want to push one object with all three properties:

    obj_report_dialog.array_report_dialog.push({
        from: fromDate,
        to: toDate,
        fabrika: fabrika
    });
    

    Then you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[0].to, and obj_report_dialog.array_report_dialog[0].fabrika. Or more likely, you'd have a loop like this:

    obj_report_dialog.array_report_dialog.forEach(function(entry) {
        // Use entry.from, entry.to, and entry.fabrika here
    });
    

    (See this answer for more options for looping through arrays.)

    But, if you really want to push them as separate objects, you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[1].to, and obj_report_dialog.array_report_dialog[2].fabrika (note the indexes going up).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

If you stringify a json, it's gonna create a string representation of your object.

To access data in a string like that we usually use JSON.parse that create an json object from a string. Which is the obj_report_dailog you had at start.

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
0

You can make object from json by using JSON.parse()

JSON.parse(json).array_report_dialog
kangsu
  • 226
  • 1
  • 6