1

I have use generate the javascript multiple object based my page result, then convert to JSON string. but JSON.stringify not display properly. I don't know why display like this. I have added example of my coding

var sample_object = [];
var sub_array = [];
sub_array["type"] = 'I';
sample_object.push(sub_array);

console.log(sample_object);
console.log(JSON.stringify(sample_object));

Result :-

[Array[0]]
    0: Array[0]
        length: 0
        type: "I"_
        _proto__: Array[0]
        length: 1__proto__:
        Array[0]

JSON.stringify Output

 [[]]

Thanks in advance!

1
  • sub_array["type"] = 'I'; This statement will have no effect Commented Jan 29, 2016 at 9:16

2 Answers 2

2

It's because you can't have named arguments in an array. You need to change sub_array to an object. Also note that the variable you have named sample_object is actually an array. Here's a working version with appropriately named variables:

var sample_array = [];
var sub_object = {};
sub_object["type"] = 'I';
sample_array.push(sub_object);

console.log(sample_array);
console.log(JSON.stringify(sample_array)); // = '[{"type":"I"}]'

Example fiddle

You can even shorten the first four lines to just this:

var sample_array = [{ type: 'I' }];
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, Worked
No problem, glad to help.
You can have custom properties in Array! Array instance is Object instance too...
0

Only Array indexes from 0 to a.length-1 are used by JSON.stringify, it is ok. If you want to create another properties, use object...

e.g.

var x={type:"i",data:[]}

1 Comment

Thanks for your help

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.