How Can I Access JSON Array Values By Index?

How can I access the elements in this JSON array (below) by index?

At the moment the following returns null
this.some_array[0]

…because I’m pretty sure I’m supposed to use…
this.some_array.asset_variation_0;

…but I really need to access them by index. Is there a way or maybe some other work around?

Thanks

 MyScript.attributes.add('some_array', {
    type: 'json',
    description:"Some description..",
    schema: [
    {
        name: 'asset_variation_0',
        type: 'string',
        default: ""
    }, {
        name: 'asset_variation_1',
        type: 'string',
        default: ""
    }, {
        name: 'asset_variation_2',
        type: 'string',
        default: ""
    }  
    ]
});

Hi @Grimmy

I’m not sure you need the JSON ScriptAttribute in this case. You are correct you would need to access these properties based on the name value you’re setting.

If you just need a simple ScriptAttribute with an array of strings, all that you would need to do is:

MyScript.attributes.add('strings', {
  type: 'string',
  title: 'Strings',
  array: true
});

You could then access each entry with:

this.strings[0]

to get the first entry.

If you REALLY need specifically an array of different types of attributes, you may want to have a look at using Object.Keys as a way to iterate over everything:

I hope this is helpful.

If I do the ScriptAttribute with an array of strings, can I access them in the inspector? Thanks

Also, just to confirm, there is no way to access the JSON using index values then?

Yes, you will be able to access the array entities when logging them to the console, as well as when you’re defining them within the editor.

I would say that there is no built-in way for that as JSON objects don’t really have index values. You can generate them in a way by using Object.Keys and then using that array of the key names to iterate over the object itself.

1 Like

How do I show the array in the inspector? Doing the following doesnt show up anything at all…

myScript.attributes.add('some_entities', {
  type: 'entity',
  title: 'Entities',
  array: true
});

If you mean the editor, after parsing the script, you should be provided with a field to specify the length of the array. After doing that, you can just fill in the resulting boxes with the entities you need. Here is an example from one of my projects showing what it looks like:

image

1 Like

Thanks. For some reason though I had to refresh the browser as well as parsing to see the array appear.

Sure thing. Here’s the relevant snippet:

var UiManager = pc.createScript('uiManager');
...
UiManager.attributes.add('goalParts', {
    type: 'entity',
    title: 'Goal Particles',
    array: true
});
...
1 Like

Thanks. I got it working. Much apprecciated!