Get and store multidimensional array not JSON in Firebase - javascript

I am using multidimensional array (not JSON) in Javascript.
var Ar = [
['1','2013','A','Name1','1','1','3','3','1','2','3','4',''],
['2','2014','B','Name2','1','2','3','1','1','2','3','5',''],
['3','2015','C','Name3','1','2','4','4','1','2','5','4','']
];
To send or store Array Ar to Firebase Cloud I use:
var data = new Firebase("xxxx.firebaseIO.com");
data.set(Ar);
I use this 2D array form a lot.
What option do I have to get or store individual data or array back from Firebase Cloud?
Like refresh and sync Array Ar with the Cloud
Store new data the cloud Ar[2][3] = "New Text"
Get value from the cloud var x = Ar[2][3]
Hope you can help
Thanks K

var array = [
['1','2013','A','Name1','1','1','3','3','1','2','3','4',''],
['2','2014','B','Name2','1','2','3','1','1','2','3','5',''],
['3','2015','C','Name3','1','2','4','4','1','2','5','4','']
];
var ref = new Firebase('https://xxxx.firebaseio.com/');
ref.set(array);
ref.on('value', function(snapshot) {
var value = snapshot.val();
console.log(value);
console.log(value[2][3]);
});
The output from the above is:
[["1", "2013", "A", "Name1", "1", "1", "3", "3", "1", "2", "3", "4", ""],
["2", "2014", "B", "Name2", "1", "2", "3", "1", "1", "2", "3", "5", ""],
["3", "2015", "C", "Name3", "1", "2", "4", "4", "1", "2", "5", "4", ""]]
"Name3"
Any time any part of the array changes, the value event will fire again and the on('value' callback will be invoked.
If you want to update the array, you have two options.
array[2][3] = "New Text";
ref.set(array);
This will send the entire array to Firebase. The alternative is to update the one the element at [2][3] straight in your database:
ref.child(2).child(3).set("Newest Text");
No matter which of the two approaches you use, the on('value' callback will be invoked again.
Check out this jsbin for a working version of the code: http://jsbin.com/nawatetuya/edit?js,console

This can be answered in the Angular Firebase API docs if you're using Angular.
Look for $save and $add to save and add data to Firebase. To get values from the database, you just have to assign a variable like
var obj = $firebaseObject(ref);
and you can get the data from the variable to the DOM like
$scope.data = obj;
Pretty simple.
You can manipulate the data before it reaches the DOM inside a factory or service first then use a controller to get or present information.

Related

Geolib and getPreciseLocation through an Array

I have an array and I need to order the data of it by the distance of a specific point.
Knowing that .sort() won't work since I'm dealing with coordinates, I've been using a library called Geolib which has a function called getPreciseLocation() which is exactly what I need, but it doesn't seem to work while iterating through an array.
Here is the array containing the data I will be using.
Data:
[
{
"id": "1",
"Point": "27.1597268, 40.6646601"
},
{
"id": "2",
"Point": "11.1640393, 49.648713"
},
{
"id": "3",
"Point": "26.1539253, 42.6599287"
},
{
"id": "4",
"Point": "21.1597268, 44.6646601"
},
{
"id": "5",
"Point": "10.1640393, 43.648713"
},
{
"id": "6",
"Point": "26.1539253, 61.6599287"
}
]
The code I've been trying to use to iterate through the array.
let DistancesFromUserLocation = [];
this.state.Data.forEach(item => {
DistancesFromUserLocation.push(geolib.getPreciseDistance({latitude: 30.1891168, longitude: 11.6226982}, item.Point))
})
As a disclaimer: I only need to get to receive the distance of each array object to a new array.
I've tried and researched many things and get around the solution, but just about thinking that I am getting to the solution, something would go wrong.
You need to push the generated distance each iteration to DistancesFromUserLocation array.
let DistancesFromUserLocation = [];
this.state.Data.forEach(item => {
// push each distance to `DistancesFromUserLocation`
DistancesFromUserLocation.push(
geolib.getPreciseDistance(
{latitude: 30.1891168, longitude: 11.6226982},
item.Point
);
)
})
Only then you can use the Array.sort().
console.log(DistancesFromUserLocation.sort());
EDIT:
Check my working example here at codesandbox.

Code by Zapier to loop through an array of objects, pulling out one value per object and then average those values

Using JavaScript for Zapier, I am trying to calculate the average value of a property from an array of object.
Here is one of the objects...
{
"code": 0,
"data": [
{
"id": "28737",
"owner": "1",
"date": "1581945706",
"dla": "0",
"dlm": "1582551517",
"system_source": "3",
"source_location": null,
"ip_addy": null,
"ip_addy_display": null,
"import_id": "0",
"contact_cat": "*/*",
"bulk_mail": "1",
"bulk_sms": "0",
"bindex": "76",
"f1849": "9898983",
"f1850": "Foundation Course 2: Lecture 1 QUIZ",
"f1851": "0",
"f1853": "John Doe",
"f1854": "TRUE",
"f1855": "93", // <= calculate average for this property
"f1859": "292",
"f1862": "0",
"f1867": "Kajabi",
"f1868": "0",
"unique_id": "7WB77PT"
},
...
]
}
I need to pull out the value for the property named f1855 for each object, then calculate the average and return that value via POST.
I don't think this is hard to do with JavaScript but I am not used to the rules and limits of Zapier.
Any help appreciated!
**Seeing the edited version of your post, I am now not sure if your input data is the data array inside the example or it is an array of those objects. If the second, then I don't know if you want an average for each object's data prop. or something else. But the code below could be part of the solution in either case.
I don't know anything about Zapier, but the JavaScript part could look something like this:
const inputData = //your array of objects
const reducer = (sum, theObject) => sum + parseFloat(theObject.f1855)
const sumF1855 = inputData.reduce(reducer, 0)
const avgF1855 = sumF1855 / inputData.length
This code does not handle error conditions (like if on of the objects were missing the f1855 property or divide by zero if inputData were empty). Hopefully it gives you an idea to get started.

How can I combine this data into one Object?

This one is a tricky one.
So, lets say I have two JS objects that are fetched via REST call, via two callbacks.
So, we have:
call1() - POST method - parsed JSON to JS object, route: {{url}}/data
call1.json:
"data": [
{
"id": "1",
"volume:" "2000"
},
{
"id": "2",
"volume:" "3000"
},
{
"id": "3",
"volume:" "4000"
},
{
"id": "4",
"volume:" "5000"
}
];
call2(req.body.id) - GET method - parsed JSON to JS object, route: {{url}}/data/:id
For example, if I pass req.body.id as = 1 got from the first response, it will open data for that id. So:
return call2(2) will return the data from this JSON: call2.json:
"data": [
{
"id": "1",
"add_data": "important string",
"add_data_2": "important string two"
},
];
The bottom line is, when doing the {{url}}/data route call - call() I need to serve all the data from {{url}}/data/:id routes, and bind them to the correct id. So, for example, the scenario I am trying to achieve is this:
Inside call(): get call1.json: data, do as many call2(req.body.id) calls as there are ids in the first object and then combine add_data and add_data_two values in the first object. So for example the final object would look like this.
console.log(response)
"data": [
{
"id": "1",
"volume:" "2000",
"add_data": "important string",
"add_data_2": "important string two"
},
{
"id": "2",
"volume:" "3000",
"add_data": "important string",
"add_data_2": "important string two"
},
{
"id": "3",
"volume:" "4000",
"add_data": "important string",
"add_data_2": "important string two"
},
{
"id": "4",
"volume:" "5000",
"add_data": "important string",
"add_data_2": "important string two"
}
];
This is what I have tried so far:
async get_data(req) {
try {
const objFirst = await call1(); //gets data
let objTwo = '';
for (let i = 0; i < objFirst.data.length; i++) {
objTwo = await call2({id: objFirst.data[i].id}) //gets data
}
return objFirst;
} catch(err) {
console.log("Error: ", err)
}
}
But it does not work. How can I get all data, and make as many as call2(id) as there are ids and combine that all in one object? Basically, I need to repeat this callback -> call2(id) as many ids we receive in call1().
Thanks, sorry if it looks like a mess.
You can use the map function and spread operator for this. Something like below.
Call2 function just simulates what an endpoint would return, but you get the idea.
var data = [
{
id: 1,
add_data: "1111"
},
{
id: 2,
add_data: "2222"
}
];
var data2 = [
{
id: 1,
volume: "bla"
},
{
id: 2,
volume: "bla"
}
];
function call2(id) {
return data2.filter(x => x.id == id)[0];
}
var result = data.map(x => {
var response = call2(x.id);
return {
...x,
...response
}
})
console.dir(result[0]);
The speed of your solution (loop through an array and doing http calls to get more data is really slow). If you have a lot of these functions that needs to combine data from different datasources, and depending on your project size, i would look into either RXJS or GraphQL (If you really need performance). RXJS have great functions to merge, combine, map etc data.
RXJS
GraphQL

Parsing JSON array created from PHP array

{
"3": {
"id": "3",
"ocena_ocena": "2",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "31.12.2015."
},
"1": {
"id": "1",
"ocena_ocena": "5",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "22.12.2015."
}
}
I am using ajax to get this JSON. I tried parsing it like this:
request.done(function(response) {
alert(response.ocena_ocena);
});
Could someone please help me with this?
I also need to know how can I do a foreach statement with json?
Since your JSON represents a JavaScript object, you should include the attribute name (if we consider JavaScript object to be a map, then, we need to use the key).
Try
response["1"].ocena_ocena
or
response["3"].ocena_ocena
Since you are returning a JSON object from server instead of an array, to iterate over its properties, you could do
for (var i in response) {
console.log(response[i].ocena_ocena);
}
or
Object.keys(response).forEach(function f(e) {console.log(response[e].ocena_ocena)})
If you could modify your server side code to return JSON that looks like this,
[
{
"id": "3",
"ocena_ocena": "2",
...
},
{
"id": "1",
"ocena_ocena": "5",
...
}
]
then you could iterate over it more easily
response.forEach(function f(e) {console.log(e.ocena_ocena)})

How to convert an array to Collection in backbone

I have an array defined as:
this.noOfHouseHold = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];
I'm trying to convert it to a Backbone Collection as:
var adultListCollection = new Backbone.Collection(this.noOfHouseHold);
It gives me the list but for 2 digit numbers, it shows something like this:
attributes: Object
0: "1"
1: "1"
I'm not able to understand as to what is wrong here or is it the wrong way I'm converting my array to collections. Please suggest. Thanks in advance!
A Backbone collection expects a list of models/hashes of attributes that can be converted to a model but you have a plain array.
You will have to transform your array to a list of hashes. Assuming your values are the ids of your models :
var lst = _.map(this.noOfHouseHold, function(val) {
return {id: val};
});
var adultListCollection = new Backbone.Collection(lst);
Backbone.Collection expects a list of models or objects (because they can be converted to Backbone.Model). In order to persist the array you have to convert those primitives into objects. Use Backbone.Collection.parse and _.map to turn your array of primitives into an array of objects:
var AdultListCollection = Backbone.Collection.extend({
parse: function (noOfHouseHold) {
var res = _.map(noOfHouseHold, function (n) {
return {id: n};
});
return res;
}
});
Now you can instantiate your Collection with an array:
var adultListCollection = new AdultListCollection(this.noOfHouseHold, {parse: true});
Example: JSFiddle

Categories