Accessing Data in the Json File - javascript

I am having hard time to access the particular json data. Here`s my json file
{
"id": "72",
"title": "Item Category Product Level Average Price Comparison",
"xLabel": null,
"yLabel": "Average Price",
"zLabel": null,
"data": [{
"avgPrice": "87",
"numProducts": "85"
}, {
"avgPrice": "60",
"numProducts": "49"
}, {
"avgPrice": "59",
"numProducts": "65"
}
I want to take the value of avgPrice and numProducts of the unique values first corresponding to the merchant name. For example In the json data, First and last merchantName is same(i.e "merchantName" : "A") . So I want to take the value of Merchant A first, and Merchant B(if it is repeated I want to complete that first and then go for the another Merchant.
var mn = [];
$.each(returnedData.data, function (index, value) {
if($.inArray(value.merchantName, mn) == -1) {
mn.push(value.merchantName);
}
});
//all the merchants name stored in mn[]
function get_items_by_merchant(merchant_name) {
var items = new Array();
$.each(returnedData.data, function (index, item) {
if(returnedData.merchantName == merchant_name)
items.push(item);
});
return items;
}
var CB_items = [];
for(var i = 0; i < mn.length; i++) {
CB_items[i] = get_items_by_merchant(mn[i]);
$.each(CB_items, function (index, item) {
var avgpricve = parseFloat(response.data[i].avgPrice);
var numproducts = parseFloat(response.data[i].numProducts);
datajson = {
x: avgpricve,
y: numproducts
}
result_data.push(datajson)
});
}
response is the data in json file, I am getting it using $.getJSON . In the above code I want to
access merchant name line response.data[i].mn[i].avgPrice.. Since that I am unable to.. Is there any way that I can do?

In the function get_items_by_merchant change this
$.each(returnedData.data, function(index, item) {
if (returnedData.merchantName == merchant_name) // There is not merchantName in returnedData.
items.push(item);
});
to
$.each(returnedData.data, function(index, item) {
if (item.merchantName == merchant_name)
items.push(item);
});
Final Code with changes:-
Demo
var result_data = [];
var mn = [];
$.each(returnedData.data, function (index, value) {
if ($.inArray(value.merchantName, mn) == -1) {
mn.push(value.merchantName);
}
});
//all the merchants name stored in mn[]
function get_items_by_merchant(merchant_name) {
var items = new Array();
$.each(returnedData.data, function (index, item) {
if (item.merchantName == merchant_name) items.push(item);
});
return items;
}
var CB_items = [];
for (var i = 0; i < mn.length; i++) {
CB_items[i] = get_items_by_merchant(mn[i]);
$.each(CB_items[i], function (index, item) {
var avgpricve = parseFloat(item.avgPrice);
var numproducts = parseFloat(item.numProducts);
datajson = {
x: avgpricve,
y: numproducts
}
result_data.push(datajson)
});
console.log(result_data)

Related

How to find the Exact word using Select 2 js?

I have integrated select2.js in my project cakephp
Js file code :
$(document).ready(function()
{
$('#RecipeIngredientId').select2().change();
$('#RecipeIngredientId').on('change', function()
{
var ingred_val = $(this).val();
$('#RecipeIngredientId').select2({
ajax: {
url: "<?php echo $this->webroot; ?>adminarea/recipe/ingredshow"+ '/' + ingred_val ,
dataType: 'json',
type: "GET",
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
}
})
})
});
We have already integrated the select 2 box js in the drop down, But we are not getting proper output
Output we are getting
while searching carrot from the dropdown ->
[0]=> baby carrot 1=> baby orange carrot [2]=> baby purple carrot
[3]=> carrot
I want to show like that : Carrot will be the first one
[0]=> carrot 1=> carrot clean [2]=> baby carrot
[3]=> baby purple carrot
( carrot ) text priorities first
Plugin we have already used :
sorter
matcher
processResult
Updated file
$(document).ready(function(){
$('#RecipeIngredientId').on('change', function()
{
var ingred_val = $(this).val();
$('#RecipeIngredientId').select2({
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.title.indexOf(ingred_val) in order){
order[v.title.indexOf(ingred_val)+1] = v.title;
} else {
order[v.title.indexOf(ingred_val)] = v.title;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
})
});
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
$('#RecipeIngredientId').select2().change();
});
You can use this script.
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.indexOf("carrot") in order){
order[v.indexOf("carrot")+1] = v;
} else {
order[v.indexOf("carrot")] = v;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
So first you can check the occurrence index the word "carrot" in data value by looping through them. We are using indexOf for this purpose. After that you will get an sorted array with least occurrence index as lower key. Now we need to remove undefined values from the generated array. So for that I have used a function called "clean" (Don't forget to add this function in your JS). And you will get the sorted Array.
Here is a Fiddle.
Update
Dynamic input value
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.indexOf("carrot") in order){
order[v.indexOf("carrot")+1] = v;
} else {
order[v.indexOf("+ingred_val+")] = v;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
Just replace "carrot" with variable ingred_val where you have set the value of select box.
Update 2
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.title.indexOf("carrot") in order){
order[v.title.indexOf("carrot")+1] = v.title;
} else {
order[v.title.indexOf("+ingred_val+")] = v.title;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
Update 3
$(document).ready(function(){
$('#RecipeIngredientId').on('change', function()
{
var ingred_val = $(this).val();
$('#RecipeIngredientId').select2({
$('#RecipeIngredientId').select2().change();
processResults: function (data) {
var order = [];
$.each(data, function(k,v){
if(v.title.indexOf(ingred_val) in order){
order[v.title.indexOf(ingred_val)+1] = v.title;
} else {
order[v.title.indexOf(ingred_val)] = v.title;
}
});
data = order.clean(undefined); //remove undefined indexes from array
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
}
})
});
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
});

How to define total length of a function(data)?

I am doing the following:
$.getJSON(url,function(data){
var totalQueries = data.length;
$.each(data, function(i, item) {
But this one looks like to be wrong:
var totalQueries = data.length;
As by the end of it I check for the last item and it never happens:
if (i === totalQueries - 1) {
myId = item.pageid;
console.log(myId);
newQuery();
}
data is object use Object.keys(data).length; to count and here you object look like,
i is parse
{
"parse": {
"title": "Colegio Nueva Granada",
"pageid": 2340380,
"text": {
"*": "<div class=...."
},
"langlinks": []
}
}

Multiple Search function through array

I'm trying to search through a list of multiple values.
Here is the an example of the values:
[
{
"color":"blue",
"medium":"Sculpture",
"place":"Garage"
}
{
"color":"red",
"medium":"Painting",
"place":"Pool"
}
]
Below is my code. Works great to find a single value. But I need to find multiple values. For example I need to look and find the results for queries such as: "red blue" or "blue Painting".
It should return results that have both word.
I don't really know how to solve this, does anybody have an idea?
Thanks a lot
function search(){
var search = $('#search').val();
if(search.length < 1) {
return null;
};
var searches = search.split(" ");
var fields = ["color","medium","place"];
var results = [];
$.each(searches, function(i, word){
var wordResult = searchInJson(word,fields,json);
if( wordResult.length > 0 ) {
results.push(wordResult);
}
});
var results = searchInJson(searches,fields,json);
displaySearchResults(results);
};
function searchInJson(search,fields,json) {
var regex = new RegExp(search);
var results = [];
$.each(json, function(i, image){
$.each(fields, function(j, fieldname){
var field = image[fieldname];
if (regex.test(field)) {
results.push( image );
}
});
});
return results;
}
Here's a quick method to try:
var list = [
{
"color":"blue",
"medium":"Sculpture",
"place":"Garage"
},
{
"color":"red",
"medium":"Painting",
"place":"Pool"
}
];
var search = "red painting";
var results = list.filter(function (el) {
var s = search.toLowerCase().split(" ");
for (var key in el) {
for (var i=0; i < s.length; i++) {
if (el[key].toLowerCase() == s[i]) { // this could use indexOf depending on if you want to match partial words
s.splice(i,1);
i--;
if (!s.length) return true;
}
}
}
return false;
});
console.log(results);

Json data reading through Javascript

I am trying to read json data from website through JavaScript. Json looks like this:
{
"status" : "success",
"prices" : [
{
"market_hash_name" : "AK-47 | Aquamarine Revenge (Battle-Scarred)",
"price" : "11.38",
"created_at" : 1460116654
},
So, I got code:
if(pricelist.prices.market_hash_name == itemName) {
var price2 = Math.round(Number(pricelist.prices.market_hash_name[itemName].price) * 1000);
I know that I am doing something wrong here, could someone help me out?
EDIT: That Function is here:
function loadItems() {
$("#refresh-button").remove();
$("#loading").addClass("active");
$.getJSON("" + bot_sids[cur_bot], function(data) {
if (data.success) {
var i = 0;
var ready = true;
var invIndexes = [];
for (var index in data.rgInventory) {
invIndexes[i] = index;
i++;
}
i = 0;
$.getJSON("", function(pricelist) {
apricething = pricelist;
if (pricelist.status) {
for (id = 0; id < invIndexes.length; id++) {
var index = invIndexes[id];
var item = data.rgDescriptions[data.rgInventory[index].classid + "_" + data.rgInventory[index].instanceid];
if (item.tradable != 1) {
continue;
}
var itemName = item.market_hash_name;
var iconUrl = item.icon_url;
console.log(itemName);
for(i=0; i<pricelist.prices.length; i++){
if (pricelist.prices[i].market_hash_name == itemName) {
var price2 = Math.round(Number(pricelist.prices[i].market_hash_name.price) * 1000);
console.log(itemName);
console.log(price2);
if (price2 >= 1) {
prices2[itemName] = price2;
items[id] = {
name: itemName,
price: price2,
iconurl: iconUrl,
classid: data.rgInventory[index].classid,
id: index,
done: true
};
} else {
items[id] = {
done: true
};
}
} else {
items[id] = {
name: itemName,
price: 0,
iconurl: iconUrl,
classid: data.rgInventory[index].classid,
id: index,
done: false
};
}
}
}
finishedLoading();
}
});
According to your data structure, you need an iteration over prices.
var price2;
pricelist.prices.some(function (item) {
if (item.market_hash_name == itemName) {
price2 = Math.round(Number(item.price) * 1000);
return true;
}
});
Try this :
if(pricelist.prices[0].market_hash_name == itemName) {
var price2 = Math.round(Number(pricelist.prices[0].market_hash_name.price) * 1000);
Your mixing some things up here. prices is an array, but you are not accessing the elements of the array, but the whole array.
Then in the number calculation, you are trying to access market_hash_name as an array, which is a string.
So the following code will walk through your prices and calculate price2 if the names match.
for(var i=0; i<pricelist.prices.length; i++){
if (pricelist.prices[i].market_hash_name === itemName) {
var price2 = Math.round(Number(pricelist.prices[i].price) * 1000);
}
}

Process javascript object from html lists

I have a html structure as,
<ul>
<li>data</li>
<li><strong>data</strong></li>
<li><span>data.name</span></li>
</ul>
I want to process it to javascript object something as below,
[
{
'index': 0,
'render': function (data) {
return data;
}
},
{
'index': 1,
'render': function (data) {
return '<strong>' + data + '</strong>';
}
},
{
'index': 2,
'render': function (data) {
return '' + data.name + '';
}
}
]
I tried this code but the data parameter which is a json object are not being resolved in render field content.
var obj = [];
$('ul li').each(function(i, content){
var row = {};
row.index = i;
row.render = function(data) {
return content;
};
obj.push(row);
});
What I am looking is this code should work,
var data = {};
data.name = 'Example';
data.link = 'http://example.com';
console.log(obj[2].render(data));
It must return Example as string.
Are you looking for a string concatenation?
https://jsfiddle.net/oeavo45w/
var obj = [];
$('ul li').each(function (i, content) {
var row = {};
row.index = i;
row.render = function (data) {
console.log(111, data)
return '' + data.name + ''
};
obj.push(row);
});
var data = {};
data.name = 'Example';
data.link = 'http://example.com';
console.log(obj[2].render(data));
Solution: Parse an HTML Object and Evaluate Text as data Variable
Grab content and split it on the variable name data, making sure to accommodate key names. Provide the resulting array to a render function that checks for key names and replaces the placeholders with data supplied in the render parameter.
var obj = [];
$('ul li').each(function(i, content){
var content_arr = content.innerHTML.split(/data\.?([^"<]+)?/);
var row = {};
row.index = i;
row.render = function(data) {
var return_string = '';
for ( ii in content_arr ) {
if ( ii % 2 ) {
if ( content_arr[ii] ) {
return_string += data[content_arr[ii]];
}
else if ( 'string' === typeof data ) {
return_string += data;
}
}
else { return_string += content_arr[ii]; }
}
return return_string;
};
obj.push(row);
});
// data object
var data = {};
data.name = 'EXAMPLE';
data.link = 'http://example.com';
// <span>EXAMPLE</span>
// or data string
data = 'testme';
console.log(obj[1].render(data));
// <strong>testme</strong>
http://jsfiddle.net/heksh7Lr/6/
(Ya, I'm guessing HTML template libraries will be more powerful.)

Categories