简体   繁体   中英

Printing JavaScript Objects from Associatve Array

What if I want to console.log only one 1(ANY) javaScript object. Currenly it displays all 1000. Please Look at Php and JS files:

Server.php

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array("coordinates" => array());

$sql = "SELECT Lng, Lat, URL FROM results LIMIT 1000";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data["coordinates"][] = $row;
    }
}
echo json_encode($data);

Index.js

{
$.ajax({
  dataType: "json",
  url: 'server.php',
  //data: [],
  data: {param: ""},
  success: function(data)
  {
    //JSON.parse(data);  
    console.log(data);
  addMarkers(data,map);
  }
});

}

It's displaying all because you're logging all. You're returning 1000 objects from your db call, which is why it's logging all.

You could find a single object by a key using something like:

data.filter(x => x.myPropValue == "myString");

And log that.

If you want your JavaScript AJAX call to not log all 1000 items, you might want to change your php code ( $sql = "SELECT Lng, Lat, URL FROM results LIMIT 1000"; ) to only send one item per call (eg replace 1000 with 1), and then adjust the Server Logic to get the respective next item on a following AJAX call.

This would also make your Server & Client faster, since it's reducing the total data amount, but would still allow 1000 or more items.

You could also try and add a parameter, so that you can tell your php code how many items your JS code needs to get.

It helps to understand the json data structure you are outputting, and how you access certain elements from an object made by that json. In your case, you end up with a single object named data (as defined by the .ajax success callback). That object then contains just one keyname with an array of objects. The keyname is coordinates . Inside each array value, is an object from your database row return.

If you simply wish to show one object from your array of objects, this is all you need:

console.log( data.coordinates[0] );

That would show the first object in the array (arrays start with [0]).

console.log( data.coordinates[999] );

That would show the last object in the array of 1000.

console.log( data.coordinates[ data.coordinates.length-1 ] );

That would show the last object in an array of a variable size, using itself as the determiner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM