1

The webpage I'm developing retrieves (product) information from the database via an ajax call to a php file. Given the array structure and related json encoded nested string in the simplified php file below, how to define the corresponding nested array in javascript in an elegant way?

I looked at the examples such as in JS nested arrays, but still get stuck...

php code:

$productinfo = array();
$productinfo['supplierA']['agreementX']['productY']['productpropertyZ'] = 'valueProductproperty';
echo json_encode($productinfo);
5
  • 3
    An array needs integer indices, no? Maybe you want an object? Commented Dec 30, 2013 at 17:20
  • What's wrong with the code you have? What's going wrong? Commented Dec 30, 2013 at 17:21
  • @scott: Ideally I'd like to use a nested associative array with keys and using the javascript object description Commented Dec 30, 2013 at 17:23
  • You're missing a ; at the end of the first line. Commented Dec 30, 2013 at 17:25
  • @Pointy: My current code uses a (complex) two dimensional array, in which the keys in the provided php code are merged. Then I just found out that php allows arrays with more than 2 dimensions (yes, my coding experience is still limited), so I'd like to improve the code... Commented Dec 30, 2013 at 17:27

1 Answer 1

4

you are trying to create an object, not an array, Arrays are ordered lists, objects are unordered key/value pairs.

This would do the job:

var obj = {"supplierA": {"agreementX": {"productY": {"productpropertyZ":"valueProductproperty"}}}};

with more than one value, this could look like this:

var obj = {
     "A": {
         "1": "asd",
         "2": {
             "I": "asdf",
             "II": "asdfg"
          }
      },
      "B": "asdfgh"
    }

for more info just go to http://json.org/

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

4 Comments

Your first example will actually throw TypeError: Cannot read property 'agreementX' of undefined
Note to OP: JavaScript objects are based on the same idea as PHP associative arrays (a mapping of string keys to values), whereas JavaScript arrays are more akin to a Java or C array (which is a strict mapping of integer indices to values). The terminology can be confusing when mixing languages that have the same terms for slightly different things.
thnx! but how to define the javascript structure if the nested $productinfo array contains more values? (which I intended to ask)
@bbuecherl: thnx for the added example (!)

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.