I am trying to call Javascript's .map() method on a backbone collection that contains a JSON that looks like this:
[
{"from":"houston","to":"austin"},
{"from":"omaha", "to":"kc"}
]
My backbone model looks like this:
var ChoiceModel = Backbone.Model.extend({});
var choiceModel = new ChoiceModel({
a:'from',
z:'omaha'
})
The problem is every JSON document I'm interested in has the Key "from" instead of the city I'm interested in. Below I am trying to filter all the JSONs with the "from" value of "omaha".
var aVar = this.model.get('a');
var zVar = this.model.get('z');
return this.collection.map(function(model){
return {
a: model.get(aVar[zVar])
};
Ideally I would be able to later call variable 'a' it would only return: {"from":"omaha", "to":"kc"}.
I've tried a few variations of the code above to no avail. How can I .map() on JSON values?
Related
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists
EDIT:
This is my query:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center;
and this is the code I'm using to save the data on firebase:
results.elements.forEach(e=>{
var ref = firebase.database().ref('/point_of_interest/');
var key = firebase.database().ref().child('point_of_interest').push().key;
var updates = {};
var data = {
città : e.tags["addr:city"],
tipologia: e.tags["amenity"],
indirizzo: e.tags["addr:street"],
nome: e.tags["name"],
lat: e.lat,
lon: e.lon
}
updates['/point_of_interest/'+key] = data;
firebase.database().ref().update(updates);
})
"results" is the response in json format
You could use something like that:
var attrs = ["addr:city", "amenity", "addr:street", "name"];
var labels = ["città ", "tipologia", "indirizzo", "nome"]
var data = { };
attrs.forEach((a, i) => {
if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
});
You could even make this more dynamic, if you can query the attribute names and labels from somewhere.
I have a local JSON dataset (outlined below) and am trying to use the _.where method to retrieve specific values from within the dataset.
JSON File
"data": [{
"singles_ranking": [116],
"matches_lost": ["90"],
"singles_high_rank": [79],
"matches_won": ["170"],
"singles_ranking/_source": ["116"],
"year_matches_won": ["11"],
"name": ["Pfizenmaier Dinah"],
"gender": ["woman"],
"_resultNumber": 1,
},{etc},{etc}];
Currently I am trying to retrieve values from within the dataset like so:
var mappedPlayers = _.map(players,function(key,val){return key});
var filteredPlayers = _.where(mappedPlayers, {name:'Pfizenmaier Dinah'});
console.log(filteredPlayers);
This currently returns undefined. I am 90% sure that this is because the key values are stored within an array however, I am not sure how I can modify this _.where condition to actually make it return the text within the value attribute.
Any help would be greatly welcomed. Thank you for reading!
With ._where it is not possible, but you can use _.filter, like so
var where = {key: 'name', value: 'Pfizenmaier Dinah'};
var filteredPlayers = _.filter(players, function (el) {
// check if key exists in Object, check is value is Array, check if where.value exists in Array
return el[where.key] && _.isArray(el[where.key]) && _.indexOf(el[where.key], where.value) >= 0;
});
Example
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
I can't find anything but basic examples of ko.observablearrays that show arrays of simple strings. I have an observable array that holds a largish JSON object with a lot of properties. I need to get the one of the objects in the array based off on the id property in the array. I have this code to get the Id:
self.selectedOrgId.subscribe(function (currentOrgId) {
alert(currentOrgId);
}, self);
my observable array is populated via an ajax get request and looks something like this:
[
{"userGuid":"37ab100e-f97b-462a-b3f4-79b8fbe24831",
"orgId":1,
"orgName":
"company ltd",
"isHiring":true,
...snip...}
more...
]
How can I look into my array and get the object with the orgId that I have?
When you need to find a specific object based on its id you can use ko.utils.arrayFirst as follow :
var selectemItemID = '1';
var selectemItem = ko.utils.arrayFirst(this.items(), function(i) {
return i.orgId == selectemItemID;
});
But you can also create an computed property that returns the selected item based on the selected item id.
self.selectedItem = ko.computed({
read : function(){
return ko.utils.arrayFirst(this.items(), function(i) {
return this.selectedOrgId() == i.orgId;
});
},
owner : self
});