1

I'm trying to loop through some data that I've passed to my JS script from PHP through AJAX.

The data is:

history: [
["1h", {
    "number": "8651",
    "event": "lock"
}],
["2h", {
    "number": "16456",
    "event": "edit"
}],
["2h", {
    "number": "90",
    "event": "edit"
}],
]

I've parsed the JSON using Jquery with:

var responseData = $.parseJSON(data);
history = JSON.parse(responseData.history);

But every attempt I've made at trying to access this data has thrown an error, or returned meta info about the object.

$.each(history, function (index, value) {
    console.log(value);
});

returns:

function go()

function back()

function forward()

function pushState()

function replaceState()

11

auto

null

How do I access the data?

The reason for parsing twice is that

console.log(typeof responseData.history); // 'string'

Trying:

$.each(responseData.history, function (index, value) {

As per gurvinder372's answer gives the error:

TypeError: cannot use 'in' operator to search for '(b - 1)' in '[["1h",{"number"...'
2
  • 3
    You're parsing twice. Commented Apr 4, 2018 at 15:10
  • You cannot parse JSON which was already parsed. Commented Apr 4, 2018 at 15:11

1 Answer 1

3

You cannot edit window.history via assignment, so you are iterating window.history object, iterate responseData.history

$.each(responseData.history, function (index, value) {

Also, as per your code

var responseData = $.parseJSON(data);

responseData is parsed into an object.

Sign up to request clarification or add additional context in comments.

6 Comments

Good catch with the implicit global assignment.
@JaredSmith That is the only thing that can explain the output OP gets when he iterate history.
responseData is already a JSON should probably be responseData is already parsed
@connexo That is what I had meant, updated nevertheless.
I tried switching to responseData.history but it seems that it wasn't parsed and is still a string. I've updated the question with the results.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.