How to iterate over json with no name - javascript

var categories= {
"art": 352,
"health-beauty": 358,
"home": 372,
"jewelry": 339,
"kids": 320
}
for(var i in categories)
{
console.log("name: " + i + "id: " + ?);
}
I'm trying to import name of categories and id to mongodb but having hard time how to get the ID of each value? Is this possible or I have to re arrange the JSON file by hand?

Your var i contains the property and object's properties can be accessed using an arraylike notation. so:
for(var i in categories) {
console.log("name: " + i + "id: " + categories[i]);
}
I recommend that you always put your curly braces on the right because not doing so would yield unexpected results:
function someFunction ()
{
return
{
prop: "Prop"
}
}
alert(someFunction().prop); // Error, it returned undefined because something called semi-colon insertion. Read about it.

Related

parse values from javascript object

I see there is a problem to get a String name from JSON object's name.
I need to parse this kind on JSON response from server.
var response = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1
}
}
It is not an Array, but the object with inner objects.
i need to parse an inner ojects name and add additional values to each object.
i want be able to do something like this:
for(var i =0; i < response.length; i++){
response[i].username = parseUsernameFromString(response[i]);
response[i].service = parseServiceFromString(response[i]);
response[i].id = parseIdString(response[i]);
}
(and also state for each task)
So the question is:
What is the best way to make it?
UPDATE
this is exactly what i have for now:
for(var key in response){
if(stringContains(response[key], "Gmail")) { response[key].service = "Gmail";}
console.log("task name: "+ response[key].service);
}
function stringContains(originalString, searchString){
if(originalString.indexOf(searchString) > -1){
return true
}
else return false;
}
For walking through Objects, you need to use for ... in loop.
The real problem is: There's a , missing in your code. See the fixed working snippet:
Snippet
var response_Parsed = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1,
service: 'Gmail',
username: 'hopaop',
id: 'sjIpW'
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1,
service: 'Gmail',
username: 'hopaop',
id: '4y4yu'
}
};
for (id in response_Parsed) {
console.log("----");
if (id.indexOf("Gmail") > -1) {
console.log("We have Gmail: " + id);
console.log("UniqueName: " + id.replace("hopaopGmail", ""));
console.log("Username: " + response_Parsed[id].username);
console.log("Email Count: " + response_Parsed[id][id.replace("hopaop", "") + "_totalEmails_count"]);
}
else
console.log("We don't have Gmail: " + id);
}
And also the right way to enumerate the through the keys of the objects, is by using Object.keys.
If the response is a String like you wrote, you should first parse the JSON-String into an Object (if you're using a library like jQuery, it's probably already a JSON, as this conversion is done by jQuery automatically):
var obj = JSON.parse(responseString);
Afterwards you may iterate through it like posted above:
for (var key in obj) {
console.log("key", key, "value", obj[key]);
}

Dynamically add link with String parameter

I have a REST backend link mywebsite/guests, which returns list of guests. In the front end, I want to display the guests as links. Here's the code
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(' + guest.id + ')">' + guest.name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
I should mention that guest.id is a string.
The console always print undefined. My question, how can I add these links with String parameters?
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(this)" data-id='+guest.id+'>' + guest.name + '</a><br>')
}
function showGuest(this) {
console.log($(this).data('id'))
}
The main issue is that you are trying to access the property of dynamically bound DOM elements in your showGuest(id) function. You should use the onClick function in the following way-
var guests = [{"id":1, "name":"John Doe"},
{"id":2, "name":"David Jones"}];
for(guest of guests) {
$('#guest_list').append('<a class="guest" data-id="'+guest.id+'">' + guest.name + '</a><br>');
}
$('#guest_list').on('click', 'a.guest', function() {
var id = $(this).attr('data-id');
$('.message').text('').append("Clicked guest with ID: "+id);
});
Working JSFiddle here - https://jsfiddle.net/2dkpsve8/
Hope this helps!
The way to approach this problem depends on the format and content of the guests variable. If you started with this object:
var guests = {
'123': {id: 123, name: 'joe'},
'234': {id: 234, name: 'jane'}
};
Then key would be "123" and "234" in the following loop, and the object values would be guests[key]:
for(var key in guests) {
$('#guest_list').append('<a onclick="showGuest(' + guests[key].id + ')">' + guests[key].name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
But if you're already using jQuery, take a look at jQuery.each for another looping option.
On the other hand, if guests is an array, as in:
var guests = [
{id:"123", name:"joe"},
{id:"234", name:"jane"}
];
then you will just want to use something like:
for(var i=0; i < guests.length; i++) {
// id is guests[i].id
// name is guests[i].name
}
Amazingly,
$('#guest_list').append('<a onclick="showGuest(' + "guest.id" + ')">' + guest.name + '</a><br>')
works fine! I don't know way. "guest.id" is replaced by the actual id of guest.

How read of Object.keys() value JSON?

How read of Object.keys() value JSON ?
I trying read value key name, but give error:
Keys dynamic
{
"marka1": {
"name": "Mika",
},
"beti1": {
"name": "Yii",
}
}
var ojson = JSON.parse(objectJson);
var keys = Object.keys(ojson); //read good key
console.log("test - " + ojson.keys[0].name); //give error
Change it to console.log("test - " + ojson[ keys[0] ].name); because keys[0] is just a string.

different javascript object keys seem to be evaluated as being the same

I'm using an object as a map and storing objects in it using the pattern map[obj.href] = obj
I'm expecting duplicate keys, but something really weird is happening:
I have 2 completely different (every field) objects stored with different keys, but when a 3rd object has the same key as 1st, a lookup is returning the 2nd object (stored with a different key), and when I do a lookup of the returned object's href, I get that same object again, as if the 2 keys are equivalent.
According to Which characters are valid/invalid in a JSON key name? and some other posts on SO, any valid string can be a key in an object, and you don't need to escape any characters, which I was worried about because of all the '/'s and '#'s.
I'm sureit's just a simple bug in my code, which I can't see it because it's 8 am and I have been up all night. Any help spotting it would be appreciated.
function parseSpellsList($)
{
var spellsList = {};
$("ul[class|='link'],ul[class$='level']").each(function() {
var obj, spell_type, links, i, link, a, span, prevObj, hashKey;
obj = {};
links = this.children;
for (i=0; i<links.length; i++) {
link = links[i];
a = link.children[0];
obj.href = a.href.replace("file:///home/ckot/rpg_app/", "").replace("scripts/", "");
obj.name = a.innerHTML.replace("<b>", "").replace("</b>", "");
hashKey = obj.href;
prevObj = null;
if ( !(spellsList.hasOwnProperty(hashKey))) {
// debug code
if ("Blood Blaze" === obj.name || "Vomit Swarm" === obj.name) {
console.log("storing " + JSON.stringify(obj, null, " ") + " with hashKey: " + hashKey);
}
spellsList[hashKey] = obj;
} else {
console.log("\nWARNING: hashKey " + hashKey + " already exists");
prevObj = spellsList[hashKey];
console.log("object we which to store with hashKey: " + hashKey + "\n" + JSON.stringify(obj, null, " ")) ;
console.log("object retrieved with hashKey: " + hashKey + "\n" + JSON.stringify(prevObj, null, " "));
console.log("object retrieved with hashKey: " + prevObj.href + "\n" + JSON.stringify(spellsList[prevObj.href], null, " ") + "\n");
}
}
});
}
when I run it I get the following output:
storing {
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
} with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
storing {
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
} with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
WARNING: hashKey advancedRaceGuide/featuredRaces/orcs.html#blood-blaze already exists
object we which to store with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
}
object retrieved with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
object retrieved with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
EDIT:
just for some context I'm using:
node v0.10.22
npm v1.4.24
and the npm modules:
jsdom v1.0.0-pre.3
jquery v2.1.1",
nvm, I was initializing obj at the start of $.each() instead of inside the nested for loop. :(
i guess I just need to get some sleep.

How to write JSON with jQuery?

I have this currencies.json file:
{
"USD": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
},
"EUR": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
}
}
I need to parse it into "#content" using jQuery. Can someone help me with a code to do this? I think jSONP is needed because the feed is from another server.
Example for output needed:
<div class="currency">USD, 325.33, 344.55, 324.55, 354.55</div>
<div class="currency">EUR, 325.33, 344.55, 324.55, 354.55</div>
// you will get from server
var obj = $.parseJSON(data); // data contains the string
for (var key in obj) {
$('<div class="currency" />')
.html(key + ', ' + $.map(obj[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
HERE is the code.
$.parseJSON is used to parse the string into the object.
Then for each currency inside object use .map() to map the values.
Join the values into a string separated by ,, append into the div and a currency name.
Resulting div append to the body.
Update (see comments):
If you want to retrieve this data cross-domain use:
$.getJSON('www.domain.com/currencies.json?callback=?', function(data) {
for (var key in data) {
$('<div class="currency" />')
.html(key + ', ' + $.map(data[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
});
Something like this should help (the data parsed from your JSON above is held in the data variable):
var $body = $("body"),
key,
$div,
txt,
innerKey;
for (key in data) {
if (data.hasOwnProperty(key)) {
$div= $("<div></div").addClass("currency");
txt = [key, ", "];
for (innerKey in data[key]) {
if (data[key].hasOwnProperty(innerKey)) {
txt.push(data[key][innerKey]);
txt.push(", ");
}
}
// Remove the trailing comma
txt.pop();
// Set the HTML content of the div and then add to the body
$div.html(txt.join("")).appendTo($body);
}
}
Here's a working example jsFiddle.
well you can access things like:
data.USD.ValueUSD will get you 325.33 so you can do something liek this. pass your data object that you get from your ajax call in ur success func to call this function:
function populateContent(data){
var $currencyDiv = $('<div class="currency"></div>'),
$currencyDiv2 = $currencyDiv.clone();
$currencyDiv.html("USD, "+data.USD.ValueUSD + ", " + data.USD.ValueEUR + ", " + data.USD.PreviousValueUSD + ", " + data.USD.PreviousValueEUR);
//do the same for currencydiv2
//append your new content divs wherever you want
$('body').append($currencyDiv);
}
A more puristic approach that could also help you understand how to iterate through objects (and is browser native and therefore not relying on jQuery)
for(var data in #YOUR_JSON_DATA# ){ // iterate through the JSON nodes
var tmp = data; // store the current node in temporary variable
for(var val in json[data]){ // iterate through the current nodes' children
tmp += ", " + json[data][val]; // this is how you access multidimensional objects. format your output as you like
}
alert(tmp); // see the output. here you could use jquery to write this into your page.
}

Categories