JSON joining data in loop using JavaScript - javascript

I have to do something like left join in sql in node with JSON data. Actually, on componentWillReceiveProps react (if it's changing anything).
my state:
const dayList = {
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": [],
"2017-11-11": [],
"2017-11-12": [],
"2017-11-13": []
}
my data to join:
const visit = {
"2017-11-11": "10:30",
"2017-11-12": "10:00",
"2017-11-12": "10:30"
}
And in componentdidmount i need to setState so that as result get that:
const dayList = {
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": [],
"2017-11-11": ["10:30"],
"2017-11-12": ["10:00","10:30"],
"2017-11-13": []
}
I know how to achieve it with .map, and another loop inside with if statement. But I am sure that there is a better approach.
What may you suggest?

Yes, actually you are right. I answered the wrong question. Is not a valid JSON neither.
But still, there is a case to do.
My very raw data from db looks like that:
[
{
"createDate": "Tue Nov 07 2017 20:56:27 GMT+0100",
"visitDate": "20171110",
"visitTime": "1030",
"doctor": {
"name": "name1"
}
},
{
"createDate": "Tue Nov 07 2017 20:56:36 GMT+0100",
"visitDate": "20171111",
"visitTime": "1000",
"doctor": {
"name": "name1"
}
},
{
"createDate": "Tue Nov 07 2017 23:30:03 GMT+0100",
"visitDate": "20171111",
"visitTime": "1030",
"doctor": {
"name": "name1"
}
}
];
and in react component and need to display it as a list of visits per day like that
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": ["10:30"],
"2017-11-11": ["10:00","10:30"],
"2017-11-12": []
"2017-11-13": []

Related

Javascript array of multiple object

How to convert the 1 object with multiple item inside to an array of object? please see the picture below to understand what i meant, thanks
var author = (`SELECT author, title, remarks, status, date FROM Transaction`, 1000, data=>{
let obj = {[author: [], book: [], condition: [], status: [], date: []]}
for(let x = 0; x < data.length; x++){
obj.author.push(data[x][0]);
obj.book.push(data[x][1]);
obj.condition.push(data[x][2]);
obj.status.push(data[x][3]);
obj.date.push(data[x][4]);
}
console.log("obj: ", obj)
return resolve(obj);
})
The Current result of console.log("obj: ", obj)
{
"authors": "testuser,testname",
"books": "440936785,440936694",
"conditions": "Very Good,New,",
"status": "Not Available,Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time),Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
What I want result:
{
"authors": "testname",
"books": "440936694",
"conditions": "New",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time)"
},
{
"authors": "testname",
"books": "440936694",
"conditions": "New,",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
You have a list of rows and want to create a list of objects. That means you have to convert every row to an object. Such a transformation is typically done with Array#map, which applies a function to every element in an array a produces a new array from the return value of that function:
const objects = data.map(row => ({
author: row[0],
book: row[1],
condition: row[2],
status: row[3],
date: row[4],
}));
The library you are using to query the database might also be able to already create an object per row (using the column names) so you don't have to do the mapping yourself.

How to compare date in JSON data using jmespath?

I have one JSON data, which contains date like jan 23,2018.
How can I compare JSON data date with the current date?
[
{
"id": "user_1",
"date": "jan 23, 2019"
},
{
"id": "user_2",
"date": "mar 3, 2017"
},
{
"id": "user_3",
"date": "feb 23, 2019"
}
]
How can I get data which has the date is more than current date using jmespath?
const array = [
{
"id": "user_1",
"date": "jan 23, 2019"
},
{
"id": "user_2",
"date": "mar 3, 2017"
},
{
"id": "user_3",
"date": "feb 23, 2019"
}
];
const newArray = array.map((value) => {
value.date = new Date(value.date).getTime();
return value;
});
console.log(newArray);
console.log('current time in milliseconds ', new Date().getTime());
/* array.forEach((value) => {
const date = new Date(value.date);
console.log(date);
}); */
// console.log('current date', new Date());
Loop array and pass date string to new Date() to get date object and then you can compare it to current date.
EDIT: Now you can directly use milisecond to compare the dates.
You can use JMESPath Custom functions to achieve that. You'll need to convert your date to epoch in order to compare the dates because JMESPath doesn't understand date object.
You can refer an example here under Custom function section: https://pypi.org/project/jmespath/
I created my own custom function to check whether a past date has surpassed current time by atleast certain amount of seconds. Here's my code:
from jmespath import functions
import time
class CustomFunctions(functions.Functions):
# the function name should always have a prefix of _func_ for it to be considered
#functions.signature({'types': ['string']}, {'types': ['number']})
def _func_hasTimeThresholdCrossed(self, jobdate, difference):
jobdate = time.strptime(jobdate,'%Y-%m-%dT%H:%M:%S.%fZ')
return time.time() - time.mktime(jobdate) > difference
options = jmespath.Options(custom_functions=CustomFunctions())
jmespath.search("hasTimeThresholdCrossed(createdAt,`1000000`)",{"createdAt":"2019-03-22T10:49:17.342Z"},options=options)

Original object referenced as I apply .map function in JavaScript

I am reading data from a json file and storing it in an object in javascript , I am using d3js library to read the file.
This is what the raw data looks like in data.json file :
{
"bitcoin": [
{
"24h_vol": null,
"date": "12/5/2013",
"market_cap": null,
"price_usd": null
},
{
"24h_vol": null,
"date": "13/5/2013",
"market_cap": null,
"price_usd": null
},
{
"24h_vol": "0",
"date": "14/5/2013",
"market_cap": "1500517590",
"price_usd": "135.3"
},...]
"bitcoin_cash": [
{
"24h_vol": null,
"date": "12/5/2013",
"market_cap": null,
"price_usd": null
},
{
"24h_vol": null,
"date": "13/5/2013",
"market_cap": null,
"price_usd": null
},...]
}
I read this and then filter some of the null entries out and also parse the date and Integer values respectively, This is the code for the same:
//Get data
d3.json("data/coins.json").then((data) => {
console.log("original data", data.bitcoin);
/*---
original data (1633) [{…}, , …]
[0 … 99]
0: {24h_vol: null, date: "12/5/2013", market_cap: null, price_usd: null}
1: {24h_vol: null, date: "13/5/2013", market_cap: null, price_usd: null}
2: {24h_vol: "0", date: Tue May 14 2013 00:00:00 GMT-0400 (Eastern Daylight Time), market_cap: 1500517590, price_usd: 135.3}
...
--------*/
//Selector listener
$("#coin-select").change(function() {
var coinType =this.value;
var coinData = data[coinType];
var cleanData = coinData.filter((d) => {
return (d.price_usd)
}).map((d) => {
d.price_usd =+ d.price_usd;
d.market_cap =+ d.market_cap;
d.date = parsedDate(d.date);
return d;
});
console.log("cleanData", cleanData)
/*------
cleanData (1631) [{…}, {…}, , …]
[0 … 99]
0: {24h_vol: "0", date: Tue May 14 2013 00:00:00 GMT-0400 (Eastern Daylight Time), market_cap: 1500517590, price_usd: 135.3}
1: {24h_vol: "0", date: Wed May 15 2013 00:00:00 GMT-0400 (Eastern Daylight Time), market_cap: 1575032004, price_usd: 141.96}
---*/
update(cleanData);
});
//Default to bitcoin
$('#coin-select')
.val('bitcoin')
.trigger('change');
});
As you can see the console output , the original data has parsed values for date,market_cap and price_usd too, not sure why this is happening.
Thanks for you time.
PS: this doesn't only happens in chrome as suggested in the question : Is Chrome's JavaScript console lazy about evaluating arrays?
Try something like this:
$("#coin-select").change(function() {
var coinType = this.value;
var coinData = data[coinType];
var cleanData = coinData.filter(x => x.price_usd)
.map(d => ({
price_usd: d.price_usd =+ d.price_usd,
market_cap: d.market_cap =+ d.market_cap,
date: parsedDate(d.date)
}));
update(cleanData);
});
This makes sure you return a new object from your map so you do not mutate the original and also cleans up some of the explicit returns you had which are not needed.

Array JSON in javascript

My json is:
[
{
"_id":{
"time":1381823399000,
"new":false,
"timeSecond":1381823399,
"machine":263168773,
"inc":-649466399
},
"asset":"RO2550AS1",
"Salt Rejection":"90%",
"Salt Passage":"10%",
"Recovery":"59%",
"Concentration Factor":"2.43",
"status":"critical",
"Flow Alarm":"High Flow"
},
[
{
"Estimated Cost":"USD 15",
"AssetName":"RO2500AS1",
"Description":"Pump Maintenance",
"Index":"1",
"Type":"Service",
"DeadLine":"13 November 2013"
},
{
"Estimated Cost":"USD 35",
"AssetName":"RO2500AS1",
"Description":"Heat Sensor",
"Index":"2",
"Type":"Replacement",
"DeadLine":"26 November 2013"
},
{
"Estimated Cost":"USD 35",
"AssetName":"RO2550AS1",
"Description":"Heat Sensor",
"Index":"3",
"Type":"Replacement",
"DeadLine":"26 November 2013"
},
{
"Estimated Cost":"USD 15",
"AssetName":"RO2550AS1",
"Description":"Pump Maintenance",
"Index":"4",
"Type":"Service",
"DeadLine":"13 November 2013"
},
{
"Estimated Cost":"USD 15",
"AssetName":"RO3000AS1",
"Description":"Pump Maintenance",
"Index":"5",
"Type":"Service",
"DeadLine":"13 November 2013"
},
{
"Estimated Cost":"USD 35",
"AssetName":"RO3000AS1",
"Description":"Heat Sensor",
"Index":"6",
"Type":"Replacement",
"DeadLine":"26 November 2013"
}
]
]
I need to access it in javascript.
The following code is not working:
var jsonobjstr = JSON.parse(jsonOutput);
alert ("asset: "+jsonobjstr.asset);
Because the entire JSON is contained in an array.
alert("asset: "+jsonobjstr[0].asset);
http://jsfiddle.net/ExplosionPIlls/yHj5X/2/
In javascript
var somename = []; means a new array and;
var somename = {}; means a new object.
Therefore if some json starts with a [] means it is a array of objects, and if it starts with {} means it is a object.
Your json starts with [], therefore it is a array of objects, so you need to access each object by doing:
json[n].asset for each position of the array (where n is a integer).
BUT:
Your JSON is weird. Looks like you will always have a array with one element (if true, the json should start with {}.
LIKE:
{
"id":
{
"code":1381823399000
},
"asset":"RO2550AS1",
"history":
[
{
"value":"USD 15"
},
{
"value":"USD 15"
},
{
"value":"USD 15"
}
]
}
Here you can do:
thing.id.code
thing.asset
thing.history[0].value
thing.history[1].value

flattening json to csv format

i am trying to convert a json value to a flat csv based on the field that is selected by user . My json looks like
var data = {
"_index": "test",
"_type": "news",
"_source": {
"partnerName": "propertyFile 9",
"relatedSources": "null",
"entityCount": "50",
"Categories": {
"Types": {
"Events": [{
"count": 1,
"term": "Time",
"Time": [{
"term": "Dec 9",
"Dec_9": [{
"count": 1,
"term": "2012"
}]
}]
}, {
"count": 4,
"term": "News",
"News": [{
"term": "Germany",
"Germany": [{
"count": 1,
"term": "Election"
}],
"currency": "Euro (EUR)"
}, {
"term": "Egypt",
"Egypt": [{
"count": 1,
"term": "Revolution"
}]
}]
}]
}
}
}};
Ive been able to collect the values of all occurences and store it as a csv, but I want to save the details from the root itself..
If I select Time, the csv output should look like,
"test", "news", "propertyFile 9","null", "50", "Events": "Time", "Dec 9", "2012"
Is it possible to flatten the json.. I will add the json fiddle link to show where Ive reached with this thing..
http://jsfiddle.net/JHCwM/
Here is an alternative way to flatten an object into key/value pairs, where the key is the complete path of the property.
let data = {
pc: "Future Crew",
retro: {
c64: "Censor Design",
amiga: "Kefrens"
}
};
let flatten = (obj, path = []) => {
return Object.keys(obj).reduce((result, prop) => {
if (typeof obj[prop] !== "object") {
result[path.concat(prop).join(".")] = obj[prop];
return result;
}
return Object.assign(result, flatten(obj[prop], path.concat(prop), result));
}, {});
}
console.log(
flatten(data)
);
Your data value is not a JSON (string) - it's an object. There are many ways to 'flatten' this object, may be this little function might be helpful:
var recMap = function(obj) {
return $.map(obj, function(val) {
return typeof val !== 'object' ? val : recMap(val);
});
}
And here's how it can be used. )
There is a npm lib just for this with a lot of options: https://mircozeiss.com/json2csv/
# Global install so it can be called from anywhere
$ npm install -g json2csv
## Generate CSV file
$ json2csv -i data.json -o out.csv --flatten-objects
Try looking here:
http://www.zachhunter.com/2011/06/json-to-csv/
and here:
How to convert JSON to CSV format and store in a variable
Try the following :
http://codebeautify.org/view/jsonviewer
Use Export to CSV button
Check this out to flatten the Json
// Convert Nested Json to Flat Json
// Check the final json in firebug console.
var fullData = {"data":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58,"Children":[]},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83,"Children":[]},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71,"Children":[]}]}
var finalData = [];
loopJson(fullData.data);
function loopJson(data) {
$.each(data, function(i, e) {
if (e.Children.length>0) {
var ccd = e.Children;
delete e.Children;
finalData.push(e);
loopJson(ccd);
} else {
delete e.Children;
finalData.push(e);
}
});
}
console.log(finalData);
Here is Js fiddle link http://jsfiddle.net/2nwm43yc/

Categories