calculate the date diff in javascript from JSON array - javascript

I have a JSON object which returns a list of events with dates and times, I want to add a counter to the next event time, but i am not sure how to approach this?
Basically, my JSON is like:
[{"name": "BAKER-CROSSROADS", "country": "USA", "lon": "165.25", "yield": "21", "lat": "11.58", "depth": ".027", "date": "1946/07/24 21:35:00", "id": "1"}, {"name": "VENUS", "country": "USA", "lon": "-116.2", "yield": "10", "lat": "37.19", "depth": ".03", "date": "1958/02/22 01:00:00", "id": "10", "fill": "green"}, {"name": "HATCHIE", "country": "USA", "lon": "-116.03", "yield": "20", "lat": "37.058", "depth": ".061", "date": "1963/02/08 16:00:01", "id": "100", "fill": "green"}, {"name": "CLIMAX:Upshot-Knothole", "country": "USA", "lon": "-116.0183", "yield": "61", "lat": "37.0875", "depth": "-.41", "date": "1953/06/04 11:14:57", "id": "1000", "fill": "red"}, {"name": "BRAVO:Castle", "country": "USA", "lon": "165.274", "yield": "15000", "lat": "11.698", "depth": "0", "date": "1954/02/28 18:45:00", "id": "1001", "fill": "red"}, ....
so for each object:
{"name": "BAKER-CROSSROADS", "country": "USA", "lon": "165.25", "yield": "21", "lat": "11.58", "depth": ".027", "date": "1946/07/24 21:35:00", "id": "1"}
{"name": "VENUS", "country": "USA", "lon": "-116.2", "yield": "10", "lat": "37.19", "depth": ".03", "date": "1958/02/22 01:00:00", "id": "10", "fill": "green"}
...
here is the code that reads the json file:
this.loadNext = function () {
d3.json("./data/detonations.json", function(datum) {
for(var i = datum.length - 1; i >= 0; --i) {
var o = datum[i];
//console.log(o);
message = {
country: o.country
,date: o.date
,depth: o.depth
,lon: o.lon
,lat: o.lat
,type: o.type
,yield: o.yield
};
self.doSomething(message)
}
});
}
i would like to calculate the date/time difference, so in this case the difference of "1958/02/22 01:00:00" and "1946/07/24 21:35:00" and pass this to the message array?

To have this difference in millisecondes, you may use
var diff = (new Date(s2)).getTime() - (new Date(s1)).getTime();
That's because the format you have is directly parsable by the Date class.

Related

How to show subtotal in vue app from firebase rtdb

I'm trying to fix this method in my vue app. It will take an array of objects that will contain the price of a selled item and needs to return the total calculation of all elements. The problem is that it will be wrong and it's not correct, into the db and console log I see the correct values, do I need to fix something in the code?
I'm saving the value that is taken from a v-model field correctly in firebase, probably I don't need the for loop?
showSubtotalSelled(items){
let sum = 0
for(let i = 0; i < items.length; i++){
console.log(i)
//if( items[i].sellPrice === items[i].selledItemsValue ){
// let parsed = items[i].sellPrice.replace(',', '.')
// sum = ( parseFloat(sum) + parseFloat(parsed) ).toFixed(2)
//} else {
let parsed = items[i].sellPrice.replace(',', '.')
console.log(parsed)
sum = ( parseFloat(sum) + parseFloat(parsed) * items[i].pz ).toFixed(2)
//}
}
if( sum === 0.00 ){
return '0,00'
} else {
return sum.replace('.', ',')
}
}
This is the firebase rtdb scheme I'm using for the items
-NJ_CNw4b8Yx1UZoNz_j
color: "GRIGIO"
id: 55
name: "TERRACES BULLDOG"
pz: "1"
sellPrice: "30,00"
size: "XL"
uid: "-NJ_CNw4b8Yx1UZoNz_j"
This is a sample of the document I load from rtdb. The calculation is 30€ more than the expected, I suppose there is something that is summed twice when the data are loaded and used to display the subtotal?
"articoliVenduti": [
null,
{
"color": "NERO",
"id": 1,
"name": "SALERNITANA ZUCCOTTO TEAM",
"pz": "1",
"sellPrice": "13",
"size": "UNICA"
},
{
"color": "GRANATA",
"id": 2,
"name": "SALERNITANA FELPA TECH",
"pz": "1",
"sellPrice": "80",
"size": "XL"
},
{
"color": "GRANATA",
"id": 3,
"name": "SALERNITANA TRAPUNTA",
"pz": "1",
"sellPrice": "55",
"size": "UNICA"
},
{
"color": "GRANATA",
"id": 4,
"name": "SALERNITANA MAGLIONE NATALIZIO",
"pz": "1",
"sellPrice": "45",
"size": "L"
},
{
"color": "MAZZOCCHI",
"id": 5,
"name": "SALERNITANA MAGLIA GARA THIRD 2022/2023",
"pz": "1",
"sellPrice": "95",
"size": "M"
},
{
"color": "BLU NAVY",
"id": 6,
"name": "LYLE SCOTT SOFTSHELL JACKET",
"pz": "1",
"sellPrice": "130",
"size": "L"
},
{
"color": "BLU NAVY",
"id": 7,
"name": "TERRACES CAPPELLO LANA",
"pz": "1",
"sellPrice": "30",
"size": "UNICA"
},
{
"color": "GIALLO",
"id": 8,
"name": "TERRACES CAPPELLO LANA",
"pz": "1",
"sellPrice": "30",
"size": "UNICA"
},
{
"color": "GRIGIO",
"id": 9,
"name": "TERRACES FELPA ZIP",
"pz": "1",
"sellPrice": "65",
"size": "XL"
},
{
"color": "BLU NAVY",
"id": 10,
"name": "TERRACES TESCHIO",
"pz": "1",
"sellPrice": "30",
"size": "XL"
},
{
"color": "GRIGIO",
"id": 11,
"name": "TERRACES BULLDOG",
"pz": "1",
"sellPrice": "30",
"size": "XL"
}
]
NB: To be more clear, data are saved correctly in rtdb, it's not there the problem, but I need to show on the vue front-end the exact calculation of all selled items that are loaded from rtdb.
You can use reduce function :
const arr = [{"color": "NERO", "id": 1, "name": "SALERNITANA ZUCCOTTO TEAM", "pz": "1", "sellPrice": "13", "size": "UNICA"}, {"color": "GRANATA", "id": 2, "name": "SALERNITANA FELPA TECH", "pz": "1", "sellPrice": "80", "size": "XL"}, {"color": "GRANATA", "id": 3, "name": "SALERNITANA TRAPUNTA", "pz": "1", "sellPrice": "55", "size": "UNICA"}, { "color": "GRANATA", "id": 4, "name": "SALERNITANA MAGLIONE NATALIZIO", "pz": "1", "sellPrice": "45", "size": "L"}, {"color": "MAZZOCCHI", "id": 5, "name": "SALERNITANA MAGLIA GARA THIRD 2022/2023", "pz": "1", "sellPrice": "95", "size": "M"}, {"color": "BLU NAVY", "id": 6, "name": "LYLE SCOTT SOFTSHELL JACKET", "pz": "1", "sellPrice": "130", "size": "L"}, {"color": "BLU NAVY", "id": 7, "name": "TERRACES CAPPELLO LANA", "pz": "1", "sellPrice": "30", "size": "UNICA"}, {"color": "GIALLO", "id": 8, "name": "TERRACES CAPPELLO LANA", "pz": "1", "sellPrice": "30", "size": "UNICA" }, {"color": "GRIGIO", "id": 9, "name": "TERRACES FELPA ZIP", "pz": "1", "sellPrice": "65", "size": "XL"}, { "color": "BLU NAVY", "id": 10, "name": "TERRACES TESCHIO", "pz": "1", "sellPrice": "30", "size": "XL"}, {"color": "GRIGIO", "id": 11, "name": "TERRACES BULLDOG", "pz": "1", "sellPrice": "30,85", "size": "XL" } ]
function showSubtotalSelled(items){
return items.reduce((a, b) => a + +b.sellPrice.replace(',', '.'), 0)
}
console.log(showSubtotalSelled(arr))

How does the script compute an object containing the frequency specified in a json data

I have a data json format (population.json) :
[
{
"Population": "100",
"City": "London",
"Date": "2020-08-07",
"Long": "70",
"Lat": "20.55"
},
{
"Population": "500",
"City": "Manchester",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
{
"Population": "800",
"City": "Manchester",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
{
"Population": "800",
"City": "London",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
]
I want to find out if there is a frequency Population > 100 in the city of Manchester and frequency Population > 100 for all city ?
I've tried using the following script:
<body>
<p>
frequency of Population > 100 in Manchester : <span id="population"></span>
</p>
</body>
for javascript :
<script>
var jsonData = 'population.json';
function getJSONValue(fileJSON) {
var value = $.ajax({
url: fileJSON,
async: false
}).responseText;
return value
}
populationData = getJSONValue(jsonData)
var populationDataJSON = JSON.parse(populationData)
for (k = 0; k < populationDataJSON.length; k++) {
var population_data = parseInt(populationDataJSON[k].population)
var Coordinate = new L.latLng(([populationDataJSON[k].Lat, populationDataJSON[k].Long]))
if (population > 100) { }
else { }
}
How do I complete this script to get the results I want it
You can use filter method on your array like this:
var data = [
{
"Population": "100",
"City": "London",
"Date": "2020-08-07",
"Long": "70",
"Lat": "20.55"
},
{
"Population": "500",
"City": "Manchester",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
{
"Population": "800",
"City": "Manchester",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
{
"Population": "800",
"City": "London",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
]
var higherThan100 = data.filter( e => e.Population > 100)
var lowerThan500 = data.filter( e => e.Population < 500)
console.log(higherThan100)
console.log(lowerThan500)
The simplest way is to use forEach:
const populationDataJSON = [{
"Population": "100",
"City": "London",
"Date": "2020-08-07",
"Long": "70",
"Lat": "20.55"
},
{
"Population": "500",
"City": "Manchester",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
{
"Population": "800",
"City": "Manchester",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
{
"Population": "800",
"City": "London",
"Date": "2020-08-07",
"Long": "70",
"Lat": "26.55"
},
];
populationDataJSON.forEach(k => {
const population_data = k["Population"];
if (population_data > 100) console.log(k);
})
k here represents each object instance, so you can access its properties like you would with: populationDataJSON[k].

How Can I able to display following data is vue js?

My json response is
{"status": true, "data": {"basic": {"name": "haji", "dob": "2018-01-01", "gender": "male", "created_at": "2018-01-08T13:38:49.767Z", "firstname": "Ah", "lastname": "Sh", "userType": "Agent", "actor": 1, "username": "ashu", "contact": {"email": "ah#gmail.com", "phone": 863249517, "address": null}, "is_new": false, "is_email_verified": true, "is_phone_verified": true}, "wallet": {"amount": 144.0, "tds": 6.0}, "clan": null, "balance_lisitings": 48, "clan_status": false, "listings": [{"pid": 36, "name": "Labs", "website": "Labs", "category": {"name": "Education"}, "location": {"lat": 9.52766533190131, "lon":
76.8221354484558, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "ah#gmail.com", "phone": 8986234851, "address": {"country": "India", "state": "Kerala", "name": "aloh", "pincode": 686895, "streetAddress": "Kottayam\nKanjirappally", "locality": "Koovappally", "city": "Koovappally"}}, "about": " IT company."}, {"pid": 37, "name": " Louis", "website": "ouis", "category": {"name": "Education"}, "location": {"lat": 10.0273434437709, "lon": 76.5288734436035, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "soew988#gmail.com", "phone": 989756240, "address": {"country": "India", "state": "Kerala", "name": "allen45", "pincode": 686518, "streetAddress": "Sppally", "locality": "Koovappally", "city": "Koovappally"}}, "about": "fsdbgfnvb cvc"}], "total_listings": 2}}
========================================================================
My vue js script is
<script>
new Vue({
el: '#listings' ,
data: {
data: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
$.ajax({
url: "https://",
method: "GET",
dataType: "JSON",
success: function (e) {
self.data = e.data;
},
});
})
},
})
</script>
My html code is
<div id="listings">
<h1>{{basic.name}}</h1>
<h2>{{basic.dob}}</h2>
like wise all data
</div>
Can anybody please help me to display the same. I am weak in js. This is the data I am getting I need to display the above data in vue js. I store all the data to a variable data[]. From it, how can I able to display the same?
One thing you'll need is a v-if to keep things from rendering when there's no data.
You have a data variable and basic is inside it. As you have it, all the things you want to include are inside it, so you will have a lot of things like data.basic.name.
const e = {
"status": true,
"data": {
"basic": {
"name": "haji",
"dob": "2018-01-01",
"gender": "male",
"created_at": "2018-01-08T13:38:49.767Z",
"firstname": "Ah",
"lastname": "Sh",
"userType": "Agent",
"actor": 1,
"username": "ashu",
"contact": {
"email": "ah#gmail.com",
"phone": 863249517,
"address": null
},
"is_new": false,
"is_email_verified": true,
"is_phone_verified": true
},
"wallet": {
"amount": 144.0,
"tds": 6.0
},
"clan": null,
"balance_lisitings": 48,
"clan_status": false,
"listings": [{
"pid": 36,
"name": "Labs",
"website": "Labs",
"category": {
"name": "Education"
},
"location": {
"lat": 9.52766533190131,
"lon": 76.8221354484558,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "ah#gmail.com",
"phone": 8986234851,
"address": {
"country": "India",
"state": "Kerala",
"name": "aloh",
"pincode": 686895,
"streetAddress": "Kottayam\nKanjirappally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": " IT company."
}, {
"pid": 37,
"name": " Louis",
"website": "ouis",
"category": {
"name": "Education"
},
"location": {
"lat": 10.0273434437709,
"lon": 76.5288734436035,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "soew988#gmail.com",
"phone": 989756240,
"address": {
"country": "India",
"state": "Kerala",
"name": "allen45",
"pincode": 686518,
"streetAddress": "Sppally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": "fsdbgfnvb cvc"
}],
"total_listings": 2
}
};
new Vue({
el: '#listings',
data: {
data: [],
},
mounted() {
const self = this;
self.data = e.data;
},
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="listings" v-if="data.basic">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>
Any data nested inside the data (and computed) property is available in the template between the {{ and }} tags.
For example:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ msg }}</h2>'
data: function () {
return {
msg: 'default message'
}
},
So in your case, with nested properties it is exactly the same as you would access them in javascript:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ data.wallet.amount }}</h2>'
'<h2 v-for="listing in listings" :key="listing.pid">{{ listing.name }}</h2>'
}
data: function () {
return {
data: []
}
},
Note
The data object should be returned from a function, from the original docs:
When defining a component, data must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we use a plain object for data, that same object will be shared by reference across all instances created! By providing a data function, every time a new instance is created we can call it to return a fresh copy of the initial data. (https://v2.vuejs.org/v2/api/#data)
Further reading
I would advise you to read the Vue guide, especially the sections about
Declarative Rendering, Conditionals and Loops and Template Syntax
EDIT
While I was writing my answer, I see you edited your question.
Change your html to this:
<div id="listings">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>

How do I filter an object that is part of an array value?

Given the following data
[
{
"date": "2017-10-04",
"games": [
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4
}
]
},
{
"date": "2017-10-14",
"games": [
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5
}
]
}
]
how do I filter out the objects so that I only show the hockey games played on that date. Essentially I need the same array of objects back, but the object should only be shown if the games key = sport: hockey
I know I can only run the filter method on arrays, but I can't figure out how to loop over the object inside of the array and return the whole object again. Any help would be greatly appreciated.
Try:
const filtered = yourArray.map(item => ({...item, games: item.games.filter(game => game.sport === 'hockey')})
// When run, this produces:
[
{
"date": "2017-10-04",
"games": [
{
"game_id": 1,
"notes": "Game was played",
"owner": "steve",
"players": "10",
"sport": "hockey",
"time": "2017-10-04T20:24:30+00:00"
},
{
"game_id": 4,
"notes": "Game was played",
"owner": "henry",
"players": "10",
"sport": "hockey",
"time": "2017-10-04T10:12:30+00:00"
}
]
},
{
"date": "2017-10-14",
"games": [
{
"game_id": 3,
"notes": "Game was played",
"owner": "steve",
"players": "4",
"sport": "hockey",
"time": "2017-10-14T20:32:30+00:00"
}
]
}
]
Which I think is what you want.
I think the following code should do the trick:
var x=[
{
"date": "2017-10-04",
"games": [
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4
}
]
},
{
"date": "2017-10-14",
"games": [
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5
}
]
}]
function filterByDate (data, date){
return data.filter(function(entry){
return sameDay(new Date(entry.date), date)
})
}
function filterBySport(data, sport){
data.forEach(function(entry){
entry.games=entry.games.filter(function(entry2){
return entry2.sport===sport
})
})
return data
}
function sameDay(date1, date2){ //helper function to check for date equality
return date1.getFullYear()===date2.getFullYear() &&
date1.getMonth()===date2.getMonth() &&
date1.getDay()===date2.getDay()
}
function myFilter(data, date, sportType){ // the final function you have to call
return filterBySport(filterByDate(data, date), sportType)
}
console.log(myFilter(x, new Date("2017-10-04"), "hockey"))
Let's take an array :-
let students = [
{"Name": "Priya","marks": [50, 60, 70, 80, 90]},
{"Name": "Ankita","marks": [80, 90, 95]}
]
Now, I want to filter marks greater than or equal to 90, The code will look like this.
students.map((student) => {
return {...student,
marks: student.marks.filter((mark) => mark >= 90)
}
})
// Result will be [{"Name": "Priya", "marks": [90]}, {"Name": "Ankita","marks": [90,95]}]
Spread operator will expand student and then it will override the marks key with filtered marks value.
If you will not use spread operator,
students.map((student) => student.marks.filter((mark) => mark >= 90))
// Result will be [[90],[90]]
Then you will get only the filtered values and not the values on which you haven't applied the filter.

Typescript model class for JSON object

I have the following JSON:
{
"-KtDGS8GdOcJ33Lcqjok": {
"2017": {
"address": "test address 1",
"area2": "3212",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Solar",
"client": "Test Contact",
"createdAt": 1504551753483,
"lastEdited": 1504551805648,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.490362758827665",
"lng": "-69.93279173970221",
"name": "17002 - test",
"pictures": {
"a95ff256-0f05-3122-a6b5-a88d3fd14c3f": true
},
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "1234",
"year": "2017"
}
},
"-KtDGaU9BB6eNj-MsyBg": {
"2015": {
"address": "test 2a",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504552100747,
"lastEdited": 1504552100747,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "15002 - test2a ",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2015"
},
"2017": {
"address": "test 2",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504551790632,
"lastEdited": 1504551790632,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "17003 - test2b",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2017"
}
},
"codeCounter": {
"2015": 2,
"2017": 5
},
"totals": {
"2015": 1,
"2017": 5
}
}
It's basically a list of objects, each object contains one or more nested objects wrapped in the year they were made (physically these are houses,apartments, etc.).
Where I'm having trouble is trying to map the 'year' objects (2017, 2015, etc') as they may or may not exist. For example, an object may have both 2017, 2016 entries or only one of them, etc.
I already have a 'Property' model class that I believe works, it has all the address, author, category, etc. fields. I'm trying to create the outter class that would contain a list of these property objects:
export interface PropertyWrapper {
[year: number]: Property;
}
I tried parsing the JSON as a PropertyWrapper[] array and this way I can already access a property by calling:
for (const pw of data) {
console.log(pw[2017]);
}
But this only works because I already know the object has a '2017' entry. How could I do this dynamically regardless of whether or not there's a '2017', '2010', or 10 entries ?
Are you looking for something like this.
First gets object keys, then loop through these keys and then loop through nested object keys
var jso = {
"-KtDGS8GdOcJ33Lcqjok": {
"2017": {
"address": "test address 1",
"area2": "3212",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Solar",
"client": "Test Contact",
"createdAt": 1504551753483,
"lastEdited": 1504551805648,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.490362758827665",
"lng": "-69.93279173970221",
"name": "17002 - test",
"pictures": {
"a95ff256-0f05-3122-a6b5-a88d3fd14c3f": true
},
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "1234",
"year": "2017"
}
},
"-KtDGaU9BB6eNj-MsyBg": {
"2015": {
"address": "test 2a",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504552100747,
"lastEdited": 1504552100747,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "15002 - test2a ",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2015"
},
"2017": {
"address": "test 2",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504551790632,
"lastEdited": 1504551790632,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "17003 - test2b",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2017"
}
},
"codeCounter": {
"2015": 2,
"2017": 5
},
"totals": {
"2015": 1,
"2017": 5
}
};
Object.keys(jso).forEach(function(key) {
Object.keys(jso[key]).forEach(function(nestedKey){
console.log(`nestedKey: ${nestedKey} \n ` , jso[key][nestedKey]);
});
});

Categories

Resources