convert php array to a javascript array

I am working with laravel, and i get a list of values from a database with this code:

$idordenes = DB::table('ordenes')->select('id')->get();

when I echo de idordenes variable I get this:

[{"factoryid":233658},{"factoryid":566981},{"factoryid":889566},{"factoryid":114789},{"factoryid":256958},{"factoryid":0},{"factoryid":0},{"factoryid":599544},{"factoryid":222364},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":555696},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},

I want to covert this in a javascript array like this:

var ordenes = [233658,566981,889566,114789,...];

I hope the help. thanks

Upvotes: 1

Views: 73

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50664

You need to use an ajax get request to get the data from php to your javascript file. You can use jQuery to make an ajax request like so:

$.ajax(
  url: "path_to_your_php_file",
  success: data => {
    var ordenes = JSON.parse(data);
    console.log(ordenes); // Ordenes is now the array in javascript
  }
);

In your php file you must "send out" the data you wish the ajax call to receive. You can do this by doing the following:

echo json_encode(array_column($idordenes, 'factoryid'));

Upvotes: 1

hong4rc
hong4rc

Reputation: 4103

Try this:

const arr = [{"factoryid":233658},{"factoryid":566981},{"factoryid":889566},{"factoryid":114789},{"factoryid":256958},/* more element */];

let newArr = arr.map(elem=>elem.factoryid);

console.log(newArr);
    

But your mean is code in php or js ?

Upvotes: 2

Related Questions