I created product database with JSON:
{
"1": {"group":"1", "name":"bmw" },
"2": {"group":"1", "name":"audi"},
"3": {"group":"2", "name":"volvo"}
}
But now I need to create an HTML drop down with all elements by group id.
I tried using Javascript .grep() but I don't have enough experience how to do that. Any help?
var all;
$.getJSON("data.json", function( data ) {
all = data;
});
var group1 = $.grep(all, function(el, i) {
return el.group. === 2
});
console.log(JSON.stringify(group1));
According to the documentation $.grep is for use with arrays, coincidentally it also has several clear examples... your JSON object is not an array but an object literal. Ideally instead of this:
{
"1": {"group":"1", "name":"bmw" },
"2": {"group":"1", "name":"audi" },
"3": {"group":"2", "name":"volvo"}
}
Your response should be coming back similar to this:
{
products: [
{"group":"1", "name":"bmw" },
{"group":"1", "name":"audi" },
{"group":"2", "name":"volvo"}
]
}
Then with a little tweaking your example will return the object's you desire in another array - take note of the difference between the === and the == operators as in your JSON example the group is returned as a string as opposed to a number.
var group1 = $.grep(all.products, function(el, i){
return el.group == 2;
});
If you still wish to work with your original JSON object (which you shouldn't as it's keys seem redundant and somewhat inefficient), then you will have to devise your own method of filtering. For example:
var group1 = {};
$.each(all, function(i, el){
if(el.group == 2) group1[i] = el;
});
Related
I am trying to wrap my head around how I might accomplish something like this, structurally:
var keywordDataProducts =
[
{"keyword" : "keyword1", "list" : [ "DP1", "DP2" ] },
{"keyword" : "keyword2", "list" : [ "DP1" ] }
];
But of course, without the values being hard coded. For instance, we currently loop through all the DP values (DP1, DP2, DP3, etc..) - which all have 0-M keywords. I'm trying to create an inverse lookup of that, where you can get all DPs that use a particular keyword. I have code that uses the structure above perfectly, but I just need the data to get populated more dynamically.
Do I initialize the var keywordDataProducts = []; declaration with anything in it, or define the structure of it having a keyword and a list (which is an array)? Or do you leave it as an array with nothing about it, and define that when you're adding items?
I've heard associative arrays can be used for a situation like this, but I'm not quite wrapping my head around that at the moment. I've also seen objects with {} usages, but there is no push there and I need an array of keywords, which also contains arrays of DPs (list). Thoughts?
You would do something like this, but you didn't clearly describe what the input look like and what output you're looking for.
function fn (input) {
var ouput = {};
input.forEach( function (DP) {
for (prop in DP) {
if (DP.hasOwnProperty(prop) {
if (output[prop]) {
output[prop].push(DP);
} else {
output[prop] = [DP];
}
}
}
});
return output;
}
This takes this kind of input
[{"alpha":...}, {"beta":..., "delta":...}, {"alpha":..., "gamma":...}]
and returns
{"alpha":[{"alpha":...}, {"alpha":..., "gamma":...}]}, "beta":{"beta":..., "delta":...}, "delta":{"beta":..., "delta":...}, "gamma":{"alpha":..., "gamma":...}}
I don't know how you want your output so I just made an object with each keyword as its own key for the DP values.
var data = [{dp: "dp1", keys: ["key1", "key2", "key3"]}, {dp: "dp2", keys: ["key1", "key2", "key3"]}, {dp: "dp3", keys: ["key1", "key2", "key3"]},];
function keyWordArray(arr) {
var newObj = {};
arr.forEach((obj) => {
obj.keys.forEach((keyVal) => {
if(newObj.hasOwnProperty(keyVal)){
newObj[keyVal].dp.push(obj.dp);
} else {
newObj[keyVal] = {dp:[obj.dp],};
}
});
});
return newObj;
}
document.getElementById("data").innerHTML = JSON.stringify(keyWordArray(data));
<div id="data">
</div>
You can treat objects as associative arrays, and you don't have to use "push" to add a new element.
// Create your object like this
var keywordDataProducts =
{
"keyword1" : { "list" : [ "DP1", "DP2"] },
"keyword2" : { "list" : [ "DP1" ] }
};
// Treat it like an associative array
var keyword1 = keywordDataProducts["keyword1"];
alert("keyword1 = " + keyword1.list.join(", "));
// Add to it like this
keywordDataProducts["keyword3"] = { "list" : ["DP3", "DP4"] };
// See the new object includes your new keyword
alert(JSON.stringify(keywordDataProducts));
// To iterate the keys of your object, you can do something like this
for(var item in keywordDataProducts)
{
if(keywordDataProducts.hasOwnProperty(item))
{
alert(item);
}
}
You can see the fiddle here;
https://jsfiddle.net/gksjtwr6/2/
Hello i want to filter json data like sql query without the help of plugins like alasql.js or linq.js or any plugins.
for example
{
"Managing PCL": [
{
"idItScreen": "1436",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListActiveTarif",
"busScreenName": "My Current Tarif"
},
{
"idItScreen": "1437",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListTermineTarif",
"busScreenName": "History Tarif"
}
]
}
for example i need to get data where idItScreen>1430 so that json data must be displayed the main challenge is to do without plugins so please reccomend me a good solution to do this without plugins
First turn your JSON into a Javascript object:
var obj = JSON.parse(myJSON);
Then do your filtering:
var matches = [];
var arr = obj['Managing PCL'];
for (var i = 0; i < arr.length; i++) {
if (arr[i].idItScreen > 1430) {
matches.push(arr[i]);
}
}
Or using jQuery.grep:
var matches = jQuery.grep(obj['Managing PCL'], function(n, i) {
return n.idItScreen > 1430;
});
Now matches contains the matching items.
If you want to get the JSON again, just use JSON.stringify:
var filteredJSON = JSON.stringify({'Managing PCL': matches});
You can also simply use .filter:
var matches = [];
var all = obj['Managing PCL'];
var filtered = all.filter(function(){
return $(this).idItScreen > 1430;
})
You don't need to use jQuery for this. You can use the filter() method of Array.prototype. See the working snippet below:
var obj = {
"Managing PCL": [{
"idItScreen": "1436",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListActiveTarif",
"busScreenName": "My Current Tarif"
}, {
"idItScreen": "1437",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListTermineTarif",
"busScreenName": "History Tarif"
}]
};
var filteredArray = obj['Managing PCL'].filter(function(item) {
return item.idItScreen > 1430;
});
obj['Managing PCL'] = filteredArray;
document.getElementById('result').innerHTML = JSON.stringify(obj);
<div id="result"></div>
You don't need jQuery for this. Use filter on the data instead.
function filterData(data, key, value) {
return data.filter(function (el) {
return el[key] > value;
});
}
// Note, `filter` operates on arrays, so you need to specify the
// array that contains the data
var result = filterData(data['Managing PCL'], 'idItScreen', '1430');
Also note that filter returns a new array containing the objects that it's found that match your criteria. You can access those objects in the usual way: result[0], for example.
DEMO
You could even expand this to create a function that returns data based on the operator too, not just greater-than, by using a look-up object:
var lookup = {
'>': function (data, value) { return data > value; },
'<': function (data, value) { return data < value; },
'===': function (data, value) { return data === value; }
}
function filterData(data, key, operator, value) {
return data.filter(function (el) {
return lookup[operator](el[key], value);
});
}
filterData(data['Managing PCL'], 'idItScreen', '>', '1430');
filterData(data['Managing PCL'], 'idItScreen', '===', '1430');
DEMO
As Iam new to javascript, I found handleBar.js can be used to template with dynamic data.
I worked on a sample which worked fine and the json structure was simple and straight forward.
(function()
{
var wtsource = $("#some-template").html();
var wtTemplate = Handlebars.compile(wtsource);
var data = { users: [
{url: "index.html", name: "Home" },
{url: "aboutus.html", name: "About Us"},
{url: "contact.html", name: "Contact"}
]};
Handlebars.registerHelper('iter', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ret = ret + fn($.extend({}, context[i], { i: i, iPlus1: i + 1 }));
}
} else {
ret = inverse(this);
}
return ret;
});
var temp=wtTemplate(data);
$("#content").html(temp);
})();
<script id="some-template" type="text/x-handlebars-template">
{{#iter users}}
<li>
{{name}}
</li>
{{/iter}}
</script>
How to iterate a json with the below structure ? Please do suggest the possible way for iterating and creating the template for the below json structure
var newData = { "NEARBY_LIST": {
"100": {
"RestaurantID": 100,
"ParentRestaurantID": 0,
"RestaurantName": "Chennai Tiffin",
"listTime": [{
"startTime": "10:00",
"closeTime": "23:30"
} ]
},
"101": {
"RestaurantID": 101,
"ParentRestaurantID": 0,
"RestaurantName": "Biriyani Factory",
"listTime": [{
"startTime": "11:00",
"closeTime": "22:00"
}]
}
}
};
Accessing the properties of an object has nothing to do with Handlebars. If you dealing with JSON and you wish to access it in general bracket or dot notation, you must first parse the JSON into a JavaScript object using the JSON.parse() function.
After this is done, you may access the properties as follows.
var property = newData['NEARBY_LIST']['100'].RestaurantName; // "Chennai Tiffin"
Here is a fiddle to illustrate.
http://jsfiddle.net/qzm0cygu/2/
I'm not entirely sure what you mean, but if your question is how you can use/read the data in newData, try this:
newData = JSON.parse(newData); //parses the JSON into a JavaScript object
Then access the object like so:
newData.NEARBY_LIST //the object containing the array
newData.NEARBY_LIST[0] //the first item (key "100")
newData.NEARBY_LIST[1] //the second item (key "101")
newData.NEARBY_LIST[0][0] //the first field of the first item (key "RestaurantID", value "100")
newData.NEARBY_LIST[0][2] //the third field of the first item (key "RestaurantName", value "Chennai Tiffin")
newData.NEARBY_LIST[0][3][0] //the first field of the fourth field of the first item (key "startTime", value "11:00")
I hope this was what you were looking for.
EDIT: as Siddharth points out, the above structure does assume you have arrays. If you are not using arrays you can access the properties by using their names as if they're in an associative array (e.g. newData["NEARBY_LIST"]["100"]. The reason I say "properties" and "as if" is because technically JavaScript doesn't support associative arrays. Because they are technically properties you may also access them like newData.NEARBY_LIST (but I don't recommend that in this case as a property name may not start with a number, so you would have to use a mix of the different notations).
On that note, I would recommend using arrays because it makes so many things easier (length checks, for example), and there are practically no downsides.
EDIT2: also, I strongly recommend using the same camelcasing conventions throughout your code. The way you currently have it (with half your properties/variables starting with capitals (e.g. "RestaurantName", "RestaurantID") and the other half being in lowerCamelCase (e.g. "listTime", "startTime")) is just asking for people (you or colleagues) to make mistakes.
My JSON contains 'products' that each have multiple values (name, manufacturer etc.)
I have the following code that allows me to pull 'products' from my JSON based on a search result acquired from a query string. It works fine, but only if the search entry is formatted exactly how it is written in the string.
How can I allow case insensitive searches yield the desired result (and ideally, partial searches)?
I believe that regular expressions are the way to go, but I've exhausted my knowledge and can't seem to get anywhere with it.
I tried to put together a fiddle but couldn't get a proper demo working, so instead I've tried to consolidate the code and comment it for clarity. Any help would be greatly appreciated :)
Parse the JSON:
var prodobjects = JSON.parse(prods);
Code to get products based on specific value:
function getData(array, type, val) {
return array.filter(function (el) {
return el[type] === val;
});
}
Code to retrieve query string:
function gup( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];}
Section of query string I want to use:
var prodresult = gup( 'search' );
Remove plusses and replace with spaces:
var removeplus = prodresult.replace(/\+/g, ' ');
Compile list of products with their 'Prodname' matching the 'search' query:
var searchname = getData(prodobjects.products, 'Prodname', removeplus);
And as requested here is a sample of the JSON. It's still in development so the null values etc. are currently being worked out (it's received through an api). This is just one of the products, but the actual string contains many in the same format (but within "products"):
var prods = JSON.stringify({"products": [
{
"Prodname": null,
"Oem": "Example OEM",
"Snippet": "Example Snippet",
"Linkto": "www.linkhere.com",
"Imagesource": "image.png",
"Category": "Category",
"Tagline": "Tagline goes here",
"Longdescription": [
{
"Paragraph": "<p>First description of the paragraph</p>"
},
null,
null,
null
],
"Features": null,
"Company": false,
"Subscribed": false,
"Tariffs": [
{
"Tarname": "Tariff one",
"Tarpaysched": "Monthly per User",
"Tarcost": "£1"
},
null,
null,
null,
null,
null
],
"Extratariffs": null
}
]
});
---UPDATE---
I managed to get it working to support partial searches and case insensitivity with the following:
function getData(array, type, val) {
return array.filter(function (el) {
if (el[type]!=null && val!=null) {
var seeker = val.toLowerCase();
var rooted = el[type].toLowerCase();
var boxfresh = rooted.indexOf(seeker);
if (boxfresh!=-1) {
return rooted
}
}
});
}
You can convert two strings to lowercase (or uppercase) to make the comparison case-insensitive.
function getData(array, type, val) {
return array.filter(function (el) {
return el[type].toLowerCase() === val.toLowerCase();
});
}
For better searching, you might want to look into fuzzy comparison, which is "a search against data to determine likely mispellings and approximate string matching".
I am trying loop through the following JSON file below:
{
"statements": [{
"subject": "A"
}, {
"predicate": "B"
}, {
"object": "C"
}, {
"subject": "D"
}, {
"predicate": "E"
}, {
"object": "F"
}]
}
As you can see, there are two subjects, two predicates and two objects. I would like to get, for instance, the value "predicate":"E". How can I do this using jQuery or D3 Javascript library. My code below retrieves the first subject "subject":"A".
$.each(data.statements[0], function(i, v){
console.log(v.uriString);
});
or in D3 (I do not know how to do this in D3):
d3.json("folder/sample.json", function(error, graph)
{ // Code is here for getting data from JSON file }
Could anyone please help me loop through the JSON file above and retrieve some particular data either with jQuery or D3 Javascript. Thank you for your help in advance.
Try this:
$(data.statements).each(function (i) {
var d = data.statements[i];
$.each(d, function (k, v) { //get key and value of object
$("body").append("<p>"+k + ":" + v+"</p>");
});
})
Fiddle here.
The reason why your code returns the first item is beacuse you selected it with data.statments[0] and afterwards loop over that one item.
With jQuery you can use the grep-method like this:
var arrayWithItem = jQuery.grep(data.statements, function( obj ) {
return obj.predicate == "E";
});
You can read more about the grep-method here
With D3js I'm not sure, I guess you have to loop through it with an if-statement.