Make use of unnamed array - javascript

I am calling an API and successfully getting back an array like this:
[ {
"absmag" : "4.85",
"speed" : "0",
"colorb_v" : "0.65",
"label" : "Sun",
"appmag" : "-26.72",
"distance_light_years" : "0",
"id" : "53794",
"hipnum" : "0",
"vy" : "0",
"updated_at" : "49:09.3",
"vx" : "0",
"vz" : "0",
"texnum" : "1",
"plxerr" : "0",
"created_at" : "49:09.3",
"plx" : "0",
"dcalc" : "0",
"z" : "0",
"luminosity" : "0.8913",
"y" : "0",
"x" : "0"
}
]
How can I reference each of these lines? I'd like to do something like:
var database = xml.responseText;
console.log(database.label);

xml.responseText is an array, you need to access on the the good index before show label :
var database = xml.responseText;
console.log(database[0].label); // Add [0] because your example is an array of one element if you have more index refer to the edit
If the response is a string, you need to parse the response before use it :
var database = JSON.parse(xml.responseText);
console.log(database[0].label);
Edit :
If your array has more than one index, you can use a foreach loop :
database.forEach(function(el) {
console.log(el.label);
})

The key to the answer actually lies in your question . . . that value IS an array . . . a single element array, whose only element is an object. As such, you have to access the array element like an array (i.e., with an index) and then, since that lone array element is an object, you have to access the object's properties like an object (i.e., with keys).
Using your example code, that would be: console.log(database[0].label); . . . [0] gets you the first (and only) element of the database array and .label gets you the value of the "label" property of that object.

If I understand it correctly, you are expecting the resulting array to contain not just one object as depicted by your original question, but it can contain a number of objects.
If that is correct then extending the correct answers by #R3tep, #talemyn and #trjast, a loop on top of this array should help as well, IMHO.
var database=xml.responseText;
var length=database.length;
for(var i=0;i<length;i+=1){
console.log(database[i].label);
}
Useful?

You could reference the label value with
var database = xml.responseText[0];
console.log(database.label);

Related

How to avoid numeric come first alignment Issue while converting string data to json array through Json Parse in Jquery

Here is the sample code of returning string data from ajax
Result = "[
{"ProductCode":"0000001",
"ProductName":"BRINJAL LONG (GREEN)",
"HQ":"43.00",
"1104":"0.00",
"4758":"20.00",
"5379":"23.00",
"964":"2.00",
"ActualQty":"0.00",
"IsCheck":"True"}
]"
I am converting string to json array through Json parse sample code here
var myproduct = []; myproduct = JSON.parse(Result);
Actually i need output like same as string return alignment order but i am getting like this numeric comes first. kindly give some advice how to avoid this auto alignment
'{964: "2.00",
1104: "0.00",
4758: "20.00",
5379: "23.00",
ProductCode: "0000001",
ProductName: "BRINJAL LONG (GREEN)",
HQ: "43.00",
ActualQty :"0.00",
IsCheck : "True"
}'
you should change your data shape, JavaScript JSON.parse() doesn't let you to control that.
a silly solution is to add a counter to the key names. it's bad because later you need to do some string manipulation to remove the counter
Result = "[
{"1.ProductCode":"0000001",
"2.ProductName":"BRINJAL LONG (GREEN)",
"3.HQ":"43.00",
"4.1104":"0.00",
"5.4758":"20.00",
"6.5379":"23.00",
"7.964":"2.00",
"8.ActualQty":"0.00",
"9.IsCheck":"True"}
]"
or change the value part and add an order item. this way you can sort things again using that order value
Result = "[
{
"ProductCode":{
"value": "0000001"
"order": 1
},
"ProductName":{
"value" : "BRINJAL LONG (GREEN)",
"order" : 2
},
....
}]"
or a better solution would be to send an array of single key-value object. this way the parse of the json, will keep the order of the array. then each item has key and value.
Result = "[
{"ProductCode":"0000001"},
{"ProductName":"BRINJAL LONG (GREEN)"},
{"HQ":"43.00"},
{"1104":"0.00"},
{"4758":"20.00"},
{"5379":"23.00"},
{"964":"2.00"},
{"ActualQty":"0.00"},
{"IsCheck":"True"}
]"
a much better solution will be to set a key for each item, it's much easier to work with without need to use Object.Keys() to get the key value.
Result = "[
{ "key" : "ProductCode", "value" :"0000001"},
{ "key" : "ProductName", "value" :"BRINJAL LONG (GREEN)"},
{ "key" : "HQ", "value" :"43.00"},
{ "key" : "1104", "value" :"0.00"},
{ "key" : "4758", "value" :"20.00"},
{ "key" : "5379", "value" :"23.00"},
{ "key" : "964", "value" :"2.00"},
{ "key" : "ActualQty", "value" :"0.00"},
{ "key" : "IsCheck", "value" :"True"}
]"
but this question just give me a hint that your problem is somewhere else. because you are relying on the order of the data. this way of coding, your code will fail when one of these items go missing, or some more get add to it.

How to create a Hashtable in javascript from a JSON by setting a value as the key?

I apologize if this is too vague, But I want to search each JSON object by a unique value and then spit out another value. I have been told it would be a good idea to create a Hash Table for this issue, but I do not know how to go about this. For example:
{
"form_key" : "basicPatientName",
"data" : "Miranda Jones",
"cid" : 2,
"pid" : 1,
"no" : "0"
}
I want to search basicPatientName and be able to pull Miranda Jones, or search basicPatientgender and pull 1.
I used a library called DefiantJS which lets me easily loop through my JSON and lets me do exactly what I am asking, but I have been told that there are too many iterations involved if I want to do this 1000+ times in the same program.
You could use this:
data = [{
"form_key" : "basicPatientName",
"data" : "Miranda Jones",
"cid" : 2,
"pid" : 1,
"no" : "0"
},
{
"form_key" : "basicPatientGender",
"data" : "1",
"cid" : 4,
"pid" : 1,
"no" : "0"
}
];
var result = {};
data.forEach(function (rec) {
result[rec.form_key] = rec.data;
});
// output result
console.log(result);
// Example look-up use:
var data = result.basicPatientName; // = Miranda Jones

The JSON parsed into HTML, how objects are mapped to corresponding HTML?

For example, the following JSON:
{
"A" : [{
name : "admin",
email:"xxx#msn.com"
},{
name : "anly",
email:"xxx#msn.com"
}]
"B" : [{
name : "beta",
email:"xxx#msn.com"
},{
name : "b",
email:"xxx#msn.com"
}]
}
Html formatted as follows:
<ul>
<li>admin</li>
<li>anly</li>
<li>besta</li>
<li>bestb</li>
</ul>
How By clicking li, found to their corresponding object?
I think the method is:
1, by traversing JSON find, but this way is time-consuming, not simple
2, which is bound to the data key and index attributes above and through the key index to find, but if some of the more complex data structures, as too cumbersome, and do not know that there is no other better way to achieve it?
The above content is translated through Google, I do not know whether a clear description of my problem?
Here are two examples of what I wrote myself realized:
http://jsfiddle.net/18q41mfr/
It all depends on your requirements. How large will this JSON object be and how frequently will it change?
For small or constantly changing JSON objects, it might be just fine to do the method 1.
For large and constant JSON objects, go with method 2. A cleaner way to achieve method 2 that you've suggested is to make use of the Underscore.js values and groupBy method.
Merge all values in your object with the var merged = _.values(object)
Group by name var formatted = _.groupBy(merged, 'name');
Resulting JSON is such:
{
admin: {
name : "admin",
email:"xxx#msn.com"
},
anly: {
name : "anly",
email:"xxx#msn.com"
},
...
}
Use the following code to get the value in your onclick event function on your li element:
formatted[this.innerHTML].email
It seems that you're already using jQuery; you can simply stuff the object references into your HTML elements using .data().
Internally, an object reference map is maintained and the HTML element stores the reference key in a special property name.
var items = {
"type_a" : [{
name : "test",
color : "red"
},{
name : "test",
color : "blue"
}],
"type_b" : [{
name : "test",
color : "orange"
},{
name : "test",
color : "yellow"
}]
};
for (var i in items) {
for (var j = 0; j < items[i].length; j++) {
$('<li>', {text: items[i][j].name})
.data(items[i][j])
.appendTo('#items');
}
}
$("#items").on("click", "li", function() {
var obj = $(this).data();
$("#detaila").html('name:' + obj.name + '<br>color:' + obj.color + '<br>' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="items"></ul>
<div id="detaila"></div>
<div id="detailb"></div>
Your second method is kind of good enough.
Maintain a global object myObjs for searching, whose keys are name and the values are object itself.
For each of the objects like:
var obj = {
name : "beta",
email:"xxx#msn.com"
}
myObjs[obj[name]] = obj; // If the name is not unique, add an id.
Then bind the key to the HTML element:
<li data-key="admin">admin</li>
When the element is clicked, find the key, query myObjs and find the obj. Something like (assume you are using jQuery):
$('ul').on('click', 'li', function() {
var $this = $(this);
var name = $this.data('key');
var obj = myObjs[name];
console.log(obj); // Here is your corresponding object.
});
Cons: extra memory
Pros: fast.

MongoDB, PHP and JavaScript

I have the following document in a MongoDB 2.0.4 and PHP 5.5*
{
"children" : [
{
"name" : "openGL::gl"
},
{
"name" : "openGL::interfaces"
},
{
"name" : "openGL::picking"
},
{
"name" : "openGL::objects"
}
],
"name" : "test"
}
Using php I want to create another collection having a copy of this document.Because I cannot use php mongo::command I am just getting a cursor for the first collection and insert this cursor into the second:
$cursor = $collection->find();
foreach($cursor as $document){
$result->insert($document);
};
$collection is the original and $result is the new one.
Now the strange thing is sometimes this works perfectly and sometimes I recieve the following:
{
"children" : {
"3" : {
"name" : "openGL::objects"
},
"0" : {
"name" : "openGL::gl"
},
"1" : {
"name" : "openGL::interfaces"
},
"2" : {
"name" : "openGL::picking"
}
},
"name" : "test"
}
And this is really bad because I am trying to get those infos into Javascript and therefore the first one (the original) is an Array whereas the second one is an object with properties.
Does somebody know why I get this and how to fix it?
So this is the solution I am using now!
$db->command(array(
"eval" => new MongoCode("function(){
db['".$toCopy."'].copyTo('".$newName."')
};"
)
));
You can copy a collection on the server with the .copyTo() method for the collection:
db.collection.copyTo("new")
There is no client transfer as there is currently being done by iterating.
If for some reason you want this to be a part of your code then there is the "runCommand" option which has a longer syntax. So in PHP code, do the longer version of this with "eval":
$db->command(array(
"eval" => new MongoCode("function(){ " .
"db.collection.find().forEach(function(doc) { " .
"db.newcollection.insert(doc); " .
"}); " .
"};"
);
));
That will run the copy on the server. Take care to read the documentation and warnings on db.eval(). And aside from all else, but much the same as you were doing, then you must re-create all indexes on the target collection that you want to use.
But in general this will be a better way than iterating over a client connection.
Have you tried to sort the cursor like:
$cursor = $collection->find();
$cursor = $cursor->sort(array('name_of_key_variable' => 1)); //sorts in ascending order
foreach($cursor as $doc) {
...
}
You might also try more of the MongoCursor options listed here:
http://www.php.net/manual/en/class.mongocursor.php at the table of contents

Global variables to pull from an associative array/object?

I have 50 dots on a page, each individual divs. When I click one, I want to use the ID to pull values out of an array. I can get the ID but I'm having trouble using that value to get stuff out of my array. Perhaps a global variable problem? Not sure. Not even sure if this is the best way to handle multiple clicks that access multiple data. Any help is appreciated!
var location0 = {"name" : "Location 1", "image" : "image1.jpg"};
$('.dot').click(function(){
var thisLocation = $(this).attr("id");
alert(thisLocation); //Returns "location0"
alert(thisLocation["image"]); //Returns "undefined"
});
Here's a fiddle.
I'd do it like this :
var locations = {
location1 : {"name" : "Location 1", "image" : "image1.jpg"},
location2 : {"name" : "Location 2", "image" : "image2.jpg"}
}
$('.dot').click(function(){
alert(locations[this.id].name);
});
​
FIDDLE
$(this).attr("id") returns a String "location0". If you want to use it you have to get an actual location0 variable, so you have to replace one of your code lines using eval() function. like this:
var thisLocation = eval($(this).attr("id"));
I would however recommend using a new array, where "location0" would be a key, then you would just need to access a key with a string like locations["location0"] and avoid using eval().
you need to access it like this:
var test = {
location0: {"name" : "Location 1", "image" : "image1.jpg"}
};
$('.dot').click(function(){
var thisLocation = $(this).attr("id");
alert(thisLocation); //Returns "location0"
alert(test[thisLocation]["image"]); //Returns "undefined"
});
​
edit: this works
Also the reason why it doesn't work for you at first place is because thisLocation is a string, not an object it self, so you need to use brackets to access objects property by passing name. I just wouldn't advice

Categories

Resources