0

I am trying to send a javascript object to PHP using JSON.stringify and I cannot find a solution. Here`s an example of what I have:

var small_array = [],
    final_array = [];

small_array["ok"] = "ok";
small_array["not_ok"] = "not_ok";

final_array.push(small_array);

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

The output is "[[]]"

Any guidance on this one? Thanks

3
  • why not take an object instead an array? Commented Jun 14, 2018 at 14:29
  • why do you want to take arrays? Commented Jun 14, 2018 at 14:31
  • I am more interested to find out a solution for this case, if possible. Commented Jun 14, 2018 at 14:31

3 Answers 3

1

You're adding non-array-entry properties to the array. That's fine in JavaScript, but JSON doesn't have the notion of non-array-entry properties in an array (JSON arrays are just ordered sequences, whereas in JavaScript arrays are fully-fledged objects that provide special treatment to certain kinds of properties — more in my [ancient] blog post A Myth of Arrays).

For those property names (keys), you'd want a plain object, not an array:

var obj         = {}, // Note {}, not []
    final_array = [];

obj["ok"] = "ok";
obj["not_ok"] = "not_ok";

final_array.push(obj);

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

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

2 Comments

[ancient] lol :)
Thank you, I got it now.
1

There are no associative arrays in javascript. They are called objects:

const smallObject = {
   ok: "not ok",
   not_ok: "ok"
};

const finalArray = [smallObject];

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

Comments

0

Objects in javacript are defined like this var obj = {}

var small_array = {},
final_array = {};

small_array["ok"] = "ok";
small_array["not_ok"] = "not_ok";

final_array = (small_array);

console.log(JSON.stringify(final_array));
VM1623:9 {"ok":"ok","not_ok":"not_ok"}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.