jQuery | Filter elements - javascript

May be you can help me:
My functions:
getMyUsers : function(callback){ /*- get users every 5 seconds*/
...
...
success: function(r) {
var users = [];
for(var i=0; i< r.users.length;i++){
if(r.users[i]){
users.push(render('user',r.users[i]));
}
}
jQuery('#chatUsers').append(users.join(''));
}
url: 'path/handler.php?action=getusers';
}
This function get my users from the server. It comes as json string like:
{
"users": [{
"name": "username_temp",
"last_activity": "16:29:16",
"gravatar": "thumb_1546278d532ea4c1cddc7a4b.jpg",
"status": "",
"usertype": "M",
"typing": "0"
}, {
"name": "admin",
"last_activity": "16:29:16",
"gravatar": "thumb_7d41870512afee28b70d5d91.jpg",
"status": "",
"usertype": "M",
"typing": "0"
}],
"total": "2"
}
render: function(template,params){
switch(template){
case "user";
arr = ['<div class="user" id="user-',params.name,'">',params.name,'</div>'];
break;
}
return arr.join('');
}
My HTML container:
<div id="chatUsers"></div>
How should I change my functions to:
Remove (filter) user(s) from my div container if it not comes in the string.
If my user already in the container skip.
If this is a new user just append it to the container.
Thanks a lot!

As I understand, you want to remove users from the DIV if they're not in the JSON; you want to skip adding them if they are in the JSON; and you want to append them if they're not in the DIV.
Well, why not just replace the contents of the DIV instead of appending to it?
jQuery('#chatUsers').html(users.join(''));

Related

Trouble displaying JSON data from music api

I am having trouble to display the top tracks of a searched artist using the LastFM api to get data. The api returns an object toptracks. I would like to grab details about each of the top tracks from that api data.
I am not sure if I am on the right track. Can someone take a look and let me know if I am doing something wrong?
Sample data from api:
{
"toptracks": {
"track": [{
"name": "Best I Ever Had",
"playcount": "3723918",
"listeners": "1086968",
"mbid": "00bde944-7562-446f-ad0f-3d4bdc86b69f",
"url": "https://www.last.fm/music/Drake/_/Best+I+Ever+Had",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "1"
}
},
{
"name": "Forever",
"playcount": "1713492",
"listeners": "668998",
"url": "https://www.last.fm/music/Drake/_/Forever",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "2"
}
}
}
function renderTracks(trackArray) {
function createHTML(track){
return `<h1>${track.name}</h1>
<h2>${track.artist[0]}</h2>
<h3>${toptracks[1].rank}</h3>
<h3>${track.playcount}</h3>`;
};
trackHTML = trackArray.map(createHTML);
return trackHTML.join("");
};
var searchString = $(".search-bar").val().toLowerCase();
var urlEncodedSearchString = encodeURIComponent(searchString);
const url = "lastFMwebsite"
axios.get(url + urlEncodedSearchString).then(function(response) {
// createHTML.push(response.data.track);
// $(".tracks-container").innerHTML = renderTracks(response.data.track);
// comented out old code above
createHTML.push(response.toptracks.track);
$(".tracks-container").innerHTML = renderTracks(response.toptracks.track);
})
I've notice that you have not parsed the response:
axios.get(url + urlEncodedSearchString).then(function(response) {
var parsed = JSON.parse(response);
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track)
});
Another correction that I can suggest is to change the track.artist[0] to track.artist["name"] once this property returns an object instead of an array.
And about this: <h3>${toptracks[1].rank}</h3>. You will be not able to access that property because at your function you are providing just the trackproperty.
In this case you have two options: provide the whole response array or add a new parameter providing this.
function renderTracks(trackArray) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks)
Or
function renderTracks(trackArray, toptracks) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track, parsed.toptracks)
I hope this can help you :)
Your input JSON is not valid. You'll need to format it correctly. Once the data is correct:
createHTML.push(response.toptracks.track[0])
or
let i = 0;
for(; i < response.toptracks.track.length; i++){
createHTML.push(response.toptracks.track[i]);
}

How to get only particular key value pair from json data and store in variable in node js

I have a sample json data,which I need to add in to different collections in mongodb.But I dont want whole json data.For example,
jsondata=
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
}}
In this json I want window key in one collection,simillarly image key in another mongo collection.
So I was thinking if I can save that key value pair in one variable,then I can add that variable in to collection.For this I was trying for each
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat) {
console.log("entering");
var b=stringdata[exKey].image;
console.log(b);
}
But I was unable to get that image key data.Is this the right approach for this?can someone help me out in this.
My expected result would be:
In one variable,The value of window key should be saved in json format.
Simillarly image and text keyvalues in another variables.
Thanks.
Why aren't you fetching window and image simply from the object as key like:
var window= jsondata.widget.window;
var image = jsondata.widget.image;
and save them in mongo db
db.window.insert(window)
db.image.insert(image)
Tell me If I understand it right.
I don't see much problem.
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat.widget) {
console.log("entering");
console.log(exKey);
if(exKey === 'image'){
db.image.insert(jsondat.widget[exKey]);
}else if(exKey === 'window'){
db.window.insert(jsondat.widget[exKey]);
}
// or db.getCollection(exKey).insert(jsondat.widget[exKey]);
}
But I would also add that normalization is not desirable in MongoDB, you should use embedding more because you won't be able to join collections later on if you want to collate data. But that's a general idea, maybe in your requirement you want different collection.
You can do it in several ways.
Method#1
var arr = [];
for(var i in jsondata.widget){
if(typeof(jsondata.widget[i])==='object'){
arr.push(jsondata.widget[i]);
}
};
console.log(arr);
Method#2
You can use unserscore utility library to get in easy
var _=require('underscore');
var arr = [];
_.each(jsondata.widget,function(o){
if(typeof(o)==='object'){
arr.push(o);
}
});
console.log(arr);
Now you can access all the object by index
Output
[ { title: 'Sample Konfabulator Widget',
name: 'main_window',
width: 500,
height: 500 },
{ src: 'Images/Sun.png', name: 'sun1', hOffset: 250 },
{ data: 'Click Here', size: 36, style: 'bold' } ]
Method#3
Try to get separate value of each inner keys
var window= jsondata.widget.window;
var image= jsondata.widget.image;
var text= jsondata.widget.text;
Edit
var obj={
"json": {
"window": {
"title": "sample",
"name": "sam"
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250
}
}
}
console.log(obj.json.window)
result-> {title: "sample", name: "sam"}

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

How to specify one attribute of a model inside a collection?

render: function () {
news.fetchMyNews();
for (var i = 1; i <= news.length; i++) {
var newsData = news.get(i);
var newsRow = JST["news/row"](newsData.attributes);
$("#news_tbody").append(newsRow);
if (newsData.is_read == 1) {
this.$('tr').attr("class", "news_read");
} else if (newsData.is_read == 0) {
this.$('tr').attr("class", "news_unread");
}
}
}
In this code newsData.attributes is retrieved well and I get the table with 3 rows rendered.
However, the newsData.is_read values are not retrieved and there is no error message at all, thus, the rows don't get styling.
news is a collection.
I wonder, what can be wrong with this?
JSON file that I'm using for testing looks like this:
[{
"id": 1,
"_type": "friends",
"message": "Your friend ...",
"is_read": 1
},
{
"id": 2,
"_type": "friends",
"message": "Your friend ...",
"is_read": 0
},
{
"id": 3,
"_type": "other",
"message": "User ...",
"is_read": 1
}]
Since newsData is a Model for getting it's attributes either .get('is_read') or newsData.attributes.is_read should be used.

Create json tree structure with children

I have a json tree structure that is appended to by pressing invoke on this fiddle : http://jsfiddle.net/adrianjsfiddlenetuser/C6Ssa/4/
Press invoke multiple tiles on the fiddle & copy/paste the produced jSon intohttp://jsonlint.com/, the produced json is not valid
I need to produce this :
{
"nodes": [
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfasfdasas",
"date": ""
}
]
}
Can this be amended so that multiple children can be added to the tree structure, I think I need to amend the var data somehow ?
Try:
var data = {nodes: []};
$("#add").on('click', function () {
data.nodes.push({
url: "some url",
date: new Date
});
$("#myDiv").text(JSON.stringify(data));
});
if not, I didn't understand your question ;)
http://jsfiddle.net/gY5yQ/
See if this helps http://jsfiddle.net/C6Ssa/12/
var data = [];
$("#add").click(add);
function add() {
data.push({
param1: "stuff",
param2:1,
param3:1
});
var sample = {};
sample.node = data
$("#myDiv").text(JSON.stringify(sample));
}

Categories