1

Can someone explain why this is happening?

var test = JSON

var date = '10-7'

test['id'] = []
test['id'][date] = [[1,2,3]]
test['id'][date].push([1,1,1])

console.log(test) // Output: { id: [ '10-7': [ [Object], [Object] ] ] }
console.log(JSON.stringify(test)) // Output: {"id":[]}
console.log(test['id'][date][0][0]) // Output: 1

What happens at stringily is what is also happening when I'm saving my JSON to a file (I use the jsonfile module). Why does it not print out my JSON like I want to?

1 Answer 1

1

Replace

test['id'] = []

with

test['id'] = {}

The explanation is that the JSON stringification of arrays uses only their indexed properties (even if undefined) that are between zero and length-1, not any other properties they may have, such as something named "10-7" (which isn't an array index, obviously).

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

1 Comment

Thanks, that did it. Can you explain what I tried to make there? And why this happened then?

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.