I have a PHP object array as follows:
array(223) {
[0]=>
object(stdClass)#5 (9) {
["id"]=>
string(2) "10"
["name"]=>
string(10) "Cyclops"
["address"]=>
string(13) "GSDG"
}
[1]=>
object(stdClass)#6 (9) {
["id"]=>
string(2) "11"
["name"]=>
string(11) "Professor X"
["address"]=>
string(8) "XX"
}
I need to convert it into a javascript array with the name and id in this format:
var characters = {
data: [{
"name": "Cyclops",
id: 10
},
{
"name": "Professor X",
id: 11
}
]
}
Here is what I have tried:
First I converted the PHP arrays to javascript objects and then used a for loop to push details of each array to a javascript object:
var js_data = <?php echo json_encode($chars) ?>;
var characters = [];
for (var i = 0; i < js_data.length; i++) {
characters.push({
data: js_data[i]
})
}
But this results in an array of objects, each having a "data" property. Here is the console.log of testVariable:
0: {…}
data: Object { id: "10", name: "Cyclops", … }
__proto__: Object { … }
1: {…}
data: Object { id: "11", name: "Professor X", … }
How do I fix this?