Javascript array of multiple object - javascript

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.

Related

How to Update an object in an array

This is my Array
$scope.tooltipsArray = [
{
date: 2018-10-10T07:03:43.835Z,
text: 'name1'
},
{
date: 2018-09-29T18:30:00.000Z,
text: 'name2'
}
];
How can I update date to locale date format like this.
$scope.tooltipsArray = [
{
date: Wed Oct 10 2018 14:05:27 GMT+0530 (India Standard Time),
text: 'name1'
},
{
date: Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time),
text: 'name2'
}
];
I have used map() to do that. But it does not work
var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });
Can anyone tell me how to do this from map() in JavaScript?
You can use the below code -
$scope.tooltipsArray = [
{
date: "2018-10-10T07:03:43.835Z",
text: 'name1'
},
{
date: "2018-09-29T18:30:00.000Z",
text: 'name2'
}
];
var vector = $scope.tooltipsArray.map(function(el) {return { 'date':new Date(el.date).toString(),'text':el.text}});
console.log(vector);
The output will be like below -
[
{date: "Wed Oct 10 2018 12:33:43 GMT+0530 (India Standard Time)", text: "name1"}
{date: "Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time)", text: "name2"}
]
Why is there a .value key after tooltipsArray?
You assigned the array to tooltipsArray, so unless there's a Proxy involved, expect to access the array through $scope.tooltipsArray.
To fix it, just remove .value.
var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });
1- Remove .value why is there in the first place?
2- You need to change the date inside the object and then return el instead of date if you just want the date to be changed, likewise:
var vector = $scope.tooltipsArray.map(function(el) {
el.date = new Date(el.date).toLocaleDateString();
return el;
});
What map function does is going through array element one by one and run the callback function, so what you have to do is update the whole object or update one entry
el.date = new Date(el.date).toLocaleDateString();

ScanFilter in DynamoDB using BETWEEN comparisonOperator

I'm trying to use the ScanFilter to filter a date using dynamoDB.
I tried looking in the docs but can't find how to structure the JSON format.
Currently I have:
"params": {
"TableName": "steprstatus2",
"ScanFilter": {
"lastModified": {
"ComparisonOperator": "BETWEEN",
"AttributeValueList": [
"Wed, 10 Oct 2018 21:09:23 GMT", "Fri, 12 Oct 2018 21:09:23 GMT"
]
}
}
}
I'm not sure what should go in the AttributeValueList, or if I have to modify my date to be a specific format in DynamoDB itself.
Thanks
Looks like I needed to use the BETWEEN comparison operator instead and provide comma separated values in my array of the same data type:
"ScanFilter": {
"lastModified": {
"ComparisonOperator": "BETWEEN",
"AttributeValueList": [
"Wed, 10 Oct 2018 00:02:59 GMT",
"Wed, 10 Oct 2018 23:46:34 GMT"
]
}
}
According to the ScanFilter AWS docs, the AttributeValueList is specified as an array of type -> value maps.
In your case, the array would look something like this:
"AttributeValueList": [
{"S": "Wed, 10 Oct 2018 21:09:23 GMT"},
{"S": "Fri, 12 Oct 2018 21:09:23 GMT"}
]
Note that the Date type is stored as an S (String) DynamoDB type.
Use BETWEEN in FilterExpression with scan query.
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();
let queryParams = {
TableName: 'tableName',
FilterExpression: '#lastModified BETWEEN :startTime AND :endTime',
ExpressionAttributeValues: {
':startTime': '2018-06-26T18:10:00.000Z',
':endTime': '2018-06-27T18:10:00.000Z'
},
ExpressionAttributeNames: { '#lastModified': 'lastModified' },
ScanIndexForward: false
};
documentClient.scan(queryParams, function (err, data) {
if (err) {
console.log('failure:scan data from Dynamo error', err);
console.log(err);
} else {
console.log('success:scan data from Dynamo data');
console.log(data);
}
});

How to ignore time-zone on new Date()?

I have JavaScript function called updateLatestDate that receive as parameter array of objects.
One of the properties of the object in array is the MeasureDate property of date type.
The function updateLatestDate returns the latest date existing in array.
Here is the function:
function updateLatestDate(sensorsData) {
return new Date(Math.max.apply(null, sensorsData.map(function (e) {
return new Date(e.MeasureDate);
})));
}
And here is the example of parameter that function receive:
[{
"Address": 54,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2009-11-27T18:10:00",
"MeasureValue": -1
},
{
"Address": 26,
"AlertType": 1,
"Area": "West",
"MeasureDate": "2010-15-27T15:15:00",
"MeasureValue": -1
},
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2012-10-27T18:10:00",
"MeasureValue": -1
}]
The function updateLatestDate will return MeasureDate value of last object in the array.
And it will look like that:
var latestDate = Sat Oct 27 2012 21:10:00 GMT+0300 (Jerusalem Daylight Time)
As you can see the time of the returned result is different from the time of the input object.The time changed according to GMT.
But I don't want the time to be changed according to GMT.
The desired result is:
var latestDate = Sat Oct 27 2012 18:10:00
Any idea how can I ignore time zone when date returned from updateLatestDate function?
As Frz Khan pointed, you can use the .toISOString() function when returning the date from your function, but if you're seeking the UTC format, use the .toUTCString(), it would output something like Mon, 18 Apr 2016 18:09:32 GMT
function updateLatestDate(sensorsData) {
return new Date(Math.max.apply(null, sensorsData.map(function (e) {
return new Date(e.MeasureDate).toUTCString();
})));
}
The Date.toISOString() function is what you need
try this:
var d = new Date("2012-10-27T18:10:00");
d.toISOString();
result:
"2012-10-27T18:10:00.000Z"
If you use moment it will be
moment('Sat Oct 27 2012 21:10:00 GMT+0300', 'ddd MMM DD DDDD HH:mm:SS [GMT]ZZ').format('ddd MMM DD YYYY HH:mm:SS')

Javascript sorting with two properties

I'm struggling with sorting two levels. The logic is as follows. If any of the objects have a status, return the most recent object with a status. If none of the objects have a status, return the most recent object without a status.
var apps = [
{ status: 'PASS',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
},
{ status: 'FAIL',
date_created: Thu Sep 02 2015 17:24:45 GMT-0700 (PDT),
},
{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT),
}
]
var desired_result = [{ status: 'PASS',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
}]
var apps_2 = [
{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
},
{ status: '',
date_created: Thu Sep 02 2015 17:24:45 GMT-0700 (PDT),
},
{ status: '',
date_created: Thu Sep 01 2015 17:24:45 GMT-0700 (PDT),
}
]
var desired_resul2 = [{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
}]
I've tried
var sorted = _.sort_by(apps, function (x) { x.date_updated });
I've also looked a few other SO questions but can't keep the objects in place after the first sort.
If I understand your question correctly, here is what you are looking for. http://jsfiddle.net/whxu5sea/3/
You need to filter the elements to ensure they have a status of ANY kind. Then sort them by date, earliest first. Then get that first value. In my example I assumed the dates where strings, but still should work.
var apps = [
{ status: 'PASS',
date_created: 'Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)'
},
{ status: 'FAIL',
date_created: 'Thu Sep 02 2015 17:24:45 GMT-0700 (PDT)',
},
{ status: '',
date_created: 'Thu Sep 01 2015 17:24:45 GMT-0700 (PDT)',
}
];
var x;
var arr = _.filter(apps, function(data) {
return !!data.status.length;
});
x = _.chain( arr.length ? arr : apps )
.sortBy(function(data) {
return new Date(data.date_created).getTime();
}).last().value();
console.log( x );
To check if it works when no status is provided: http://jsfiddle.net/whxu5sea/4/
I hope this helps. LMK if any further clarification is needed.
EDIT: Updated to get NEWEST element (last).
Here is a simple solution that iterates just once through apps, without a filtering step. See here for a jsfiddle.
The concept is that, if status is falsy, its date is converted into a negative number that retains the correct sort order among all falsy elements, but makes all falsy elements have a lower sort order than all non-falsy ones.
We convert the falsy element dates by subtracting 8640000000000001, which is (the maximimum millis in a Date, plus one).
var x = _.chain(apps).sortBy(function(x) {
var date = new Date(x.date_created).getTime();
return x.status ? date : date - 8640000000000001;
}).last().value();
console.log( x );

Using JSON.parse() with date fields?

Let's say you have the following object as a string:
var timecard = {
"name": "Joe",
"time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)"
}
// as string
var stringed = 'var timecard = { "name": "Joe", "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }'
and you run JSON.parse(stringed) to parse it into the object. How would you go about having it convert the date into an actual Date object as opposed to a string?
Thanks!
The JSON data format doesn't have a date type, so you have to write the code to transform it into a Date object yourself.
You can pass a reviver function as the second argument to JSON.parse to do that.
function parseDate(k, v) {
if (k === "time") {
return new Date(v);
}
return v;
}
var json = '{ "name": "Joe", "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }';
var data = JSON.parse(json, parseDate);
console.log(data);

Categories