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);
}
}
Related
I'm trying to sort the following array so that the most recent event_end is first
{
"results":[
{
"event_start":"2017-11-27T09:00:00Z",
"event_end":"2017-11-27T09:00:00Z",
"attendance":0,
"title":"Administrate Training Session",
"type":"delegate"
},
{
"event_start":"2018-02-01T09:00:00Z",
"event_end":"2018-02-01T09:00:00Z",
"attendance":0,
"title":"Health and Safety Awareness (HSA)",
"type":"delegate"
},
{
"event_start":"2018-02-19T09:00:00Z",
"event_end":"2018-04-30T09:00:00Z",
"attendance":0,
"title":"SMSTS",
"type":"delegate"
}
]
}
My current code (and this is after trying almost all the different ways to do this is):
Array.from(outcome).sort(sortFunction);
function sortFunction(a, b){
if(b[3] === a[3]){
return 0;
} else {
return (b[3] < a[3]) ? -1 : 1;
}
}
And just to give clarity to how the array is being created:
var history = JSON.parse(body);
var outcome = {};
var key = 'results';
outcome[key] = [];
history.forEach(delegate => {
var data = null;
var sessionKey;
var attendanceCount = 0;
var sessionCount = 0;
var attended = 0;
Array.from(delegate['session_attendance']).forEach(function(val){
if(!val.__proto__.__proto__){
sessionCount++;
}
});
var type;
for(var k in delegate['session_attendance']){
sessionKey = k;
if(k['status'] == true){
attendanceCount++;
}
}
if(attendanceCount == 0){
attended = attendanceCount;
} else {
(attendanceCount / sessionCount) * 100
}
if(delegate['registration']['booking_contact'] !== null){
if(delegate['registration']['booking_contact']['id'] == delegate['contact']['id']){
type = 'booking_contact';
}
} else{
type = 'delegate';
}
data = {
'objectId': delegate['id'],
'title': delegate['event']['title'],
'event_start': delegate['event']['start'],
'event_end': delegate['session_attendance'][sessionKey]['start'],
'attendance': attended,
'type': type
}
outcome[key].push(data);
})
I'm sure its obvious but can anyone point me in the direction of where I am going wrong and how to sort it appropriately?
var obj = {
"results":[
{
"event_start":"2017-11-27T09:00:00Z",
"event_end":"2017-11-27T09:00:00Z",
"attendance":0,
"title":"Administrate Training Session",
"type":"delegate"
},
{
"event_start":"2018-02-01T09:00:00Z",
"event_end":"2018-02-01T09:00:00Z",
"attendance":0,
"title":"Health and Safety Awareness (HSA)",
"type":"delegate"
},
{
"event_start":"2018-02-19T09:00:00Z",
"event_end":"2018-04-30T09:00:00Z",
"attendance":0,
"title":"SMSTS",
"type":"delegate"
}
]
}
obj.results.sort((a, b) => {
return new Date(b.event_end) - new Date(a.event_end)
})
console.log(obj.results)
The function that sort receives get 2 params, each param is an obj, so you can access its properties.
Something like this should work:
arr.sort((a, b) => {
return a.event_end > b.event_end ? -1 : 1;
})
I wrote my code to search string for keywords and extracting needed data, but I have problems when I'm trying to search with keywords in arrays named: sort, title and artist. When I'm doing it I get an error about potential infinite loop.
var type = ['track','tracks','song','songs','album','albums'];
var artist = ['created by', 'made by'];
var genre = ['genre'];
var limit = ['set limit'];
var title = ['title','name'];
var sort = ['sort by', 'classificate by', 'separate by'];
var sortBy = ['popularity'];
// function changeWordsToNumbers(words) {
// if (msg.numbers[words])
// return msg.numbers[words];
// }
function searchForIndex(instruction, keywords) {
for (i = 0; i < keywords.length; i++) {
let search = instruction.search(keywords[i]);
if (search)
return search;
}
return false;
}
function getSearchResult(wanted) {
var searchResult = {
artist : searchForIndex(wanted, artist),
genre : searchForIndex(wanted, genre),
limit : searchForIndex(wanted, limit),
type : searchForIndex(wanted, type),
title : searchForIndex(wanted, title),
sort : searchForIndex(wanted, sort),
sortBy : searchForIndex(wanted, sortBy)
};
return searchResult;
}
function removeJunkKeyword(searchResult,instruction) {
for(var property in searchResult) {
if(searchResult.hasOwnProperty(property)) {
if(searchResult[property] != - 1) {
instruction = instruction.slice(0, searchResult[property] - 1);
}
}
}
return instruction;
}
function checkExist(searchResult) {
for(var property in searchResult) {
if(searchResult.hasOwnProperty(property)) {
if(searchResult[property] != -1)
return false;
}
}
return true;
}
function findAndCleanQuery(instruction, keywords) {
var exist = instruction.search(keywords);
var result = instruction.slice(exist + keywords.length + 1, instruction.length);
var searchResult = getSearchResult(result);
if (exist != -1) {
if (checkExist(searchResult)) {
return result;
} else {
result = removeJunkKeyword(searchResult,result);
return result;
}
}
return false;
}
function searchFor(instruction, keywords) {
for (i = 0; i < keywords.length; i++) {
let result = findAndCleanQuery(instruction,keywords[i]);
if (result)
return result;
}
return false;
}
function searchForType(instruction) {
for (i = 0; i < type.length; i++) {
let search = instruction.search(type[i])
if(search)
return type[i];
}
return false;
}
function searchForKeywords(instruction) {
msg.artist = searchFor(instruction, artist);
msg.type = searchForType(instruction, type);
msg.genre = searchFor(instruction, genre);
msg.limit = searchFor(instruction, limit);
msg.title = searchFor(instruction, title);
msg.sort = searchFor(instruction, sortreg);
}
var msg = {}
msg.instruction = 'Search for me';
searchForKeywords(msg.instruction);
console.log(msg.artist);
console.log(msg.type);
console.log(msg.genre);
console.log(msg.limit);
console.log(msg.title);
console.log(msg.sort);
Link for code: https://repl.it/J4Mc/9
PS. The object msg is used by node-red to communicate between nodes.
The issue is that you're doing this on several of your loops:
for (i = 0; i < keywords.length; i++) {
...where you should be doing this instead:
for (let i = 0; i < keywords.length; i++) {
Without using let, the variable i is effectively global. Each time you went into a new loop it got reset to 0, so it was never able to increase, which created the infinite loop.
As a side note, you'll also notice sortreg is undefined when it's used on line 98.
If I have the following:
var dataContainer = [
{ id : 1, value : 5, qty : 73, orders: 7 },
{ id : 2, value : 6.15, qty : 212, orders: 49},
{ id : 3, value : 12.11, qty : 29, orders : 6}
];
How do I update the value of the object using JavaScript? I have been trying the following:
function UpdateValues(passedId) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
thisData = dataContainer[i];
if (thisData.id == passedId) {
// I am updating the values in thisData
}
}
// Not sure what to do here in order to get thisData values back into dataContainer
}
So I tried to pop the dataContainer[i] and push the thisData back on but this didn't work. Unless I'm doing it incorrectly? What should I be doing here? I appreciate any help.
function UpdateValues(passedId, prop, newValue) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
thisData = dataContainer[i];
if (thisData.id == passedId) {
thisData[prop] = newValue;
}
}
}
//Change qty to 99999 for object with index of 1
UpdateValues(1, "qty", 99999);
I've added a fiddle that prints out the result as well: http://jsfiddle.net/4UH9e/
function UpdateValues(passedId) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
var data = dataContainer[i];
for (i in data) {
thisData[i] = data[i];
}
if (thisData.id == passedId) {
//Update the values in thisData.
}
}
//You still have the original data in dataContainer
}
I have an array of objects. Every object in the array has an id and an item property that is an array containing other object. I need to be able to find an element in an array by id. Here is a sample of what I have done so far, but the recursive function is always returning undefined.
How can I quit the function and return the item when I have called the function recursively several times?
$(function () {
var treeDataSource = [{
id: 1,
Name: "Test1",
items: [{
id: 2,
Name: "Test2",
items: [{
id: 3,
Name: "Test3"
}]
}]
}];
var getSubMenuItem = function (subMenuItems, id) {
if (subMenuItems && subMenuItems.length > 0) {
for (var i = 0; i < subMenuItems.length; i++) {
var item;
if (subMenuItems[i].Id == id) {
item = subMenuItems[i];
return item;
};
getSubMenuItem(subMenuItems[i].items, id);
};
};
};
var searchedItem = getSubMenuItem(treeDataSource, 3);
alert(searchedItem.id);
});
jsFiddle
You should replace
getSubMenuItem(subMenuItems[i].items, id);
with
var found = getSubMenuItem(subMenuItems[i].items, id);
if (found) return found;
in order to return the element when it is found.
And be careful with the name of the properties, javascript is case sensitive, so you must also replace
if (subMenuItems[i].Id == id) {
with
if (subMenuItems[i].id == id) {
Demonstration
Final (cleaned) code :
var getSubMenuItem = function (subMenuItems, id) {
if (subMenuItems) {
for (var i = 0; i < subMenuItems.length; i++) {
if (subMenuItems[i].id == id) {
return subMenuItems[i];
}
var found = getSubMenuItem(subMenuItems[i].items, id);
if (found) return found;
}
}
};
I know its late but here is a more generic approach
Array.prototype.findRecursive = function(predicate, childrenPropertyName){
if(!childrenPropertyName){
throw "findRecursive requires parameter `childrenPropertyName`";
}
let array = [];
array = this;
let initialFind = array.find(predicate);
let elementsWithChildren = array.filter(x=>x[childrenPropertyName]);
if(initialFind){
return initialFind;
}else if(elementsWithChildren.length){
let childElements = [];
elementsWithChildren.forEach(x=>{
childElements.push(...x[childrenPropertyName]);
});
return childElements.findRecursive(predicate, childrenPropertyName);
}else{
return undefined;
}
}
to use it:
var array = [<lets say an array of students who has their own students>];
var joe = array.findRecursive(x=>x.Name=="Joe", "students");
and if you want filter instead of find
Array.prototype.filterRecursive = function(predicate, childProperty){
let filterResults = [];
let filterAndPushResults = (arrayToFilter)=>{
let elementsWithChildren = arrayToFilter.filter(x=>x[childProperty]);
let filtered = arrayToFilter.filter(predicate);
filterResults.push(...filtered);
if(elementsWithChildren.length){
let childElements = [];
elementsWithChildren.forEach(x=>{
childElements.push(...x[childProperty]);
});
filterAndPushResults(childElements);
}
};
filterAndPushResults(this);
return filterResults;
}
I have these JavaScript entities: Item and Items.
var exports = {};
exports.Item = function(item) {
if (item) {
for (var attr in this.attributes) {
var value = item[attr];
if (value !== undefined) {
this.attributes[attr] = value;
}
}
}
return this;
};
exports.Item.prototype.attributes = {
_id: "",
title: ""
};
exports.Items = function(items) {
if (items && items.length > 0) {
for (var i = 0; i < items.length; i++) {
this.add(items[i]);
}
}
};
exports.Items.prototype.arr = [];
exports.Items.prototype.add = function(item) {
if (item) {
item = new exports.Item(item);
this.arr.push(item.attributes);
}
};
exports.Items.prototype.toJSON = function() {
var json = [];
for (var i = 0; i < this.arr.length; i++) {
json.push(this.arr[i]);
}
return json;
};
var i1 = new exports.Item({
_id: "1",
title: "1"
});
var i2 = new exports.Item({
_id: "2",
title: "2"
});
var i3 = new exports.Item({
_id: "3",
title: "3"
});
var items = new exports.Items([i1,i2,i3]);
console.log(items.toJSON());
There is a problem which I cannot find. When I execute the following code I get the last item 3 times instead of all the items.
I am sure the mistake is something small I cannot see. Maybe you can help me?
Member variables shouldn't be initialized in the prototype. Prototype variables will be shared across all instances. Instead, define the members in the constructor. So, instead of this:
exports.Items.prototype.arr = [];
Do this:
exports.Items = function(items) {
this.arr = []; // instance variable
if (items && items.length > 0) {
for (var i = 0; i < items.length; i++) {
this.add(items[i]);
}
}
};