Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Bastet's avatar

Pushing to create a multidimensional array

I'm trying to push data into my resources object and I need it to look like this

"a role" => [
    'role' => 'a role',
    'fee' => 123
];

The issue I'm getting is this

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')

If I console.log(response.data') I get my array and I have tried doing this

this.resources.push(response.data);

but that doesn't work as I would like it, my resources lands up looking like this

0 => [
    "a role" => [
        'role' => 'a role',
        'fee' => 123
    ];
]

which is close, but not how I need it to be.

Here is my code that I have at the moment

<script>
export default {
    data(){
        return {
            roleName: null,
            roleFees: null,
            resources: {},
        }
    },
    methods: {
        newRole(){
            axios.post(`/role/create`, {
                role: this.roleName,
                fees: this.roleFees
            }).then(response => {
                Object.keys(response.data).forEach(data => {
                    this.resources[data].push({
                           role: response.data[data].role,
                           fees: response.data[data].fees,
                       })
                });
                
            })
        },
    },
    mounted(){

    }
}
</script>
0 likes
2 replies
LaryAI's avatar
Level 58

The issue is that this.resources is initialized as an object, but you're trying to push to it as if it were an array. Instead, you should initialize it as an array and push new objects to it. Here's an updated version of your code:

<script>
export default {
    data(){
        return {
            roleName: null,
            roleFees: null,
            resources: [],
        }
    },
    methods: {
        newRole(){
            axios.post(`/role/create`, {
                role: this.roleName,
                fees: this.roleFees
            }).then(response => {
                Object.keys(response.data).forEach(data => {
                    this.resources.push({
                        [data]: {
                            role: response.data[data].role,
                            fees: response.data[data].fees,
                        }
                    });
                });
            })
        },
    },
    mounted(){

    }
}
</script>

This code initializes this.resources as an empty array, and then pushes new objects to it that have a key of data and a value of an object with role and fees properties. The resulting array should have the structure you're looking for.

MohamedTammam's avatar

Add it like

this.resources[response.data.role] = response.data;

Please or to participate in this conversation.