This is my code:
var deliveries = [
{
"id": 1,
"destination": 'Oakland',
"orderPrice": 75,
"rushDelivery": true,
"rushDeliveryFee": 12.75,
"orderDate": "4 April 2016"
},
{
"id": 2,
"destination": 'San Jose',
"orderPrice": 62.75,
"orderDate": "5 April 2016"
},
{
"id": 3,
"destination": 'San Francisco',
"orderPrice": 15.00,
"rushDelivery": true,
"rushDeliveryFee": 50.75,
"orderDate": "10 April 2016"
},
{
"id": 4,
"destination": 'San Francisco',
"orderPrice": 25,
"orderDate": "4/11/2016"
},
{
"id": 5,
"destination": 'San Francisco',
"orderPrice": 90,
"rushDelivery": true,
"rushDeliveryFee": 30,
"orderDate": "April 12, 2015"
},
{
"id": 6,
"destination": 'Berkeley',
"orderPrice": 45,
"orderDate": "4/01/2015"
},
{
"id": 7,
"destination": 'Berkeley',
"orderPrice": 62.16,
"orderDate": "12 April 2016"
}
];
var orderPrices = deliveries.reduce(function(prev, current) {
return prev.orderPrice + current.orderPrice
})
console.log(orderPrices);
When I console.log prev.orderPrice in the first iteration of reduce() it prints undefined, but from what I understand, if you give no second argument(the initialValue) to reduce(), it simply defaults to the first element of the array to which you apply the function to. I would expect the first object of the array to be printed. In fact, if we try this with another simpler array like var arr = [1,2,3,4,5], prev prints 1 in the first iteration.
Why is this happening?
The elements in array are reduced 1 by 1 from left to right. Thus, from the second iteration, the prev argument is the current total value already:
var orderPrices = deliveries.reduce(function (prev, current) {
if (prev.orderPrice)
{
return prev.orderPrice + current.orderPrice;
}
return prev + current.orderPrice;
});
console.log(orderPrices);
Related
I have an array of object and I want to copy that array of object to another array while modifying some items, like copying id only by ascending order and copying only the value of trophies of basketball to trophies. How to do it?
const item = [{
"id": 33,
"name": "John"
"trophies": {
"basketball" : 2,
"baseball" : 5
},
"profile": "profile/212"
}
{
"id": 12,
"name": "Michael"
"trophies": {
"basketball" : 6,
"baseball" : 7
},
"profile": "profile/341"
}
]
I want the above array of object after copying to look something like
const item2 = [{
"id": 12,
"name": "Michael"
"trophies": 6,
"profile": "http://collegeprofile.com/profile/341"
},
{
"id": 33,
"name": "John"
"trophies": 2,
"profile": "http://collegeprofile.com/profile/212"
}
]
You can sort by id ascending order using Array.prototype.sort
And map basketball value to trophies using Array.prototype.map.
const item = [{
"id": 33,
"name": "John",
"trophies": {
"basketball": 2,
"baseball": 5
},
"profile": "profile/212"
}, {
"id": 12,
"name": "Michael",
"trophies": {
"basketball": 6,
"baseball": 7
},
"profile": "profile/341"
}];
const output = item.sort((a, b) => (a.id - b.id)).map((item) => ({
...item,
trophies: item.trophies.basketball,
profile: "http://collegeprofile.com/" + item.profile
}));
console.log(output);
I'm trying to make an upcoming event on react native, I have this object
const calendatData = [
{
"data": [
{
"id": 25,
"title": "Spotify",
"name": "Family",
"service_id": 1,
"repetition": "Monthly",
"price": "79000",
"upcoming_date": [
"2020-08-07T13:35:44.606Z"
]
},
{
"id": 26,
"title": "Netflix",
"name": "Mobile",
"service_id": 2,
"repetition": "Monthly",
"price": "49000",
"upcoming_date": [
"2020-08-18T13:35:44.600Z",
"2020-08-07T13:35:44.606Z"
]
},
{
"id": 27,
"title": "iTunes",
"name": "Weekly Special",
"service_id": 3,
"repetition": "Weekly",
"price": "22000",
"upcoming_date": [
"2020-08-07T13:35:44.606Z",
"2020-08-14T13:35:44.606Z",
"2020-08-21T13:35:44.606Z",
"2020-08-28T13:35:44.606Z"
]
}
],
"status": "success"
}
]
what I've been trying to do is to extract that object based on the upcoming_date.
the result that I need is like this
upcomingData = [
{
date: '2020-08-07',
title: [
'Spotify',
'Netflix',
'iTunes'
]
},
{
date: '2020-08-18',
title: ['Netflix']
},
{
date: '2020-08-14',
title: ['iTuunes']
},
{
date: '2020-08-21',
title: ['iTuunes']
},
{
date: '2020-08-28',
title: ['iTuunes']
}
]
On the same date, if there are multiple titles, it should be grouped under the same date in the object.
instead what I got was this object
upcomingData = [
{
title: [
"Spotify",
"Netflix",
"iTunes",
],
date : [
"2020-08-29",
"2020-08-07",
"2020-08-18",
"2020-08-07",
"2020-08-07",
"2020-08-14",
"2020-08-21",
"2020-08-28",
]
}
]
I am new to this, and I'm aware that this is mostly about javascript knowledge, any help would be appreciated.
thanks
The ideas are:
First, iterate your object by Array.prototype.map() and set a unique map key from the converted date.
Then push the title to every map's key.
Actually your final map(here is myMap) will be your expected upcomingData. To output as your expected object, you can make it in your own way.
const calendarData = [{ "data": [{ "id": 25, "title": "Spotify", "name": "Family", "service_id": 1, "repetition": "Monthly", "price": "79000", "upcoming_date": ["2020-08-07T13:35:44.606Z"] }, { "id": 26, "title": "Netflix", "name": "Mobile", "service_id": 2, "repetition": "Monthly", "price": "49000", "upcoming_date": ["2020-08-18T13:35:44.600Z", "2020-08-07T13:35:44.606Z"] }, { "id": 27, "title": "iTunes", "name": "Weekly Special", "service_id": 3, "repetition": "Weekly", "price": "22000", "upcoming_date": ["2020-08-07T13:35:44.606Z", "2020-08-14T13:35:44.606Z", "2020-08-21T13:35:44.606Z", "2020-08-28T13:35:44.606Z"] }], "status": "success" }];
var myMap = new Map();
calendarData[0].data.map(element => {
var dates = [];
element.upcoming_date.map(date => {
var upcoming_date = date.slice(0,10);
if (!myMap.get(upcoming_date)) {
myMap.set(upcoming_date, []);
}
dates.push(upcoming_date);
});
var len = dates.length;
for (let i = 0; i < len; i++) {
myMap.get(dates[i]).push(element.title);
}
});
var upcomingData = [];
for (const entry of myMap.entries()) {
var obj = {};
obj["date"] = entry[0];
obj["title"] = entry[1];
upcomingData.push(obj);
}
console.log(upcomingData);
You may
traverse your source array with Array.prototype.reduce() building up the Map where trimmed portion of your date string is used as a key and the object of desired format as a value
extract Map values, using Map.prototype.values() into resulting array
Following is a quick live demo:
const src = [{"data":[{"id":25,"title":"Spotify","name":"Family","service_id":1,"repetition":"Monthly","price":"79000","upcoming_date":["2020-08-07T13:35:44.606Z"]},{"id":26,"title":"Netflix","name":"Mobile","service_id":2,"repetition":"Monthly","price":"49000","upcoming_date":["2020-08-18T13:35:44.600Z","2020-08-07T13:35:44.606Z"]},{"id":27,"title":"iTunes","name":"Weekly Special","service_id":3,"repetition":"Weekly","price":"22000","upcoming_date":["2020-08-07T13:35:44.606Z","2020-08-14T13:35:44.606Z","2020-08-21T13:35:44.606Z","2020-08-28T13:35:44.606Z"]}],"status":"success"}],
result = [...src[0].data
.reduce((r,{upcoming_date, title}) => (
upcoming_date.forEach((s,_,__,date=s.slice(0,10)) =>
r.set(
date,
{date, title: [...(r.get(date)?.title||[]), title]}
)),r),
new Map())
.values()
]
console.log(result)
.as-console-wrapper{min-height:100%;}
I have following output. it gives my API.
{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}}
I want to Push them to arrays according to method. As an example
twoHundArray=[
{ "x":2018,6,11,12,45,
"y" :1},
{"x": 2016,11,11,17,10 ,
"y" :47}]
fourhundrArry=[{ "x":2018,11,11,16,50,
"y" :5}]
without using if/else statement how to push them to different arrays. In here I don't know all the names of methods.so cannot use if statement for "method".that is the problem here.
The original object is invalid. You can't have elements in an object without specifying the keys. I've assumed that it is an array.
Secondly, there is no way of pushing elements to different arrays without knowing their names. So the judgement of pushing the elements to different variables will have to be based on if/else conditions. Additionally, creation of those variables will vary based on the groups, as method could have been any value.
If you agree to group the objects based on the values method have, here is a way to do this:
const data = [{"_id":{"year":2018,"month":6,"day":11,"hour":12,"interval":45,"method":"200"},"count":1},{"_id":{"year":2016,"month":11,"day":11,"hour":16,"interval":50,"method":"404"},"count":5},{"_id":{"year":2016,"month":11,"day":11,"hour":17,"interval":10,"method":"200"},"count":47}];
const res = {};
data.forEach(item => {
const { method, ...obj } = item['_id'];
res[method] = res[method] || [];
res[method].push({
x: Object.values(obj),
y: item.count
});
});
console.log(res);
It creates an object, whose keys are method. The values in the object are the arrays, which contain the items grouped by method.
You can use Array.reduce and create a map based on method. Try the following:
var data = [{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}];
var method = data.reduce((a,o)=>{
if(!a[o._id.method]){
a[o._id.method] = [];
};
var { method, ...ob } = o._id;
a[o._id.method].push({
"x": Object.values(ob).join(","),
"y" : o.count
});
return a;
}, {});
console.log(method);
You can create an object with status:values key/pair using Array.reduce and post that using Object destructuring and default assignment, create independent variables.
const arr = [{"_id":{"year":2018,"month":6,"day":11,"hour":12,"interval":45,"method":"200"},"count":1},{"_id":{"year":2016,"month":11,"day":11,"hour":16,"interval":50,"method":"404"},"count":5},{"_id":{"year":2016,"month":11,"day":11,"hour":17,"interval":10,"method":"200"},"count":47}];
let obj = arr.reduce((a,c) => {
a[c._id.method] = a[c._id.method] || [];
a[c._id.method].push({"x" : Object.values(c._id).join(), "y" : c.count});
return a;
},{});
/* You can add an entry here for every status type, it will pick the
** value from object and if not present will be defaulted to an empty array */
const {200 : twoHundArray=[], 404 : fourHundArray=[], 300 : threeHundArray=[]} = obj;
console.log(twoHundArray);
console.log(fourHundArray);
console.log(threeHundArray);
#Palani, I'll suggest you to use an object to gather all the required information.
Please have a look at the below code and let me know any suggestions/modifications if you need.
var timeDataArr = [
{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}
]
// An object that maps 'method' to its related data array
var newTimeData = {}
for(var timeData of timeDataArr) {
var obj = timeData["_id"];
var arr = [obj["year"], obj["month"], obj["day"], obj["hour"], obj["interval"]];
var newObj = {
"x": arr.join(", "),
"y": timeData["count"],
}
if(newTimeData[obj["method"] + "Array"]) { // method found
newTimeData[obj["method"] + "Array"].push(newObj)
} else { // method not found
newTimeData[obj["method"] + "Array"] = [newObj]
}
}
// PRETTY PRINTING OBJECT
console.log(JSON.stringify(newTimeData, undefined, 4))
/*...
{
"200Array": [
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
],
"404Array": [
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
}
...*/
// PRETTY PRINTING ARRAY POINTED BY '200Array' key
console.log(JSON.stringify(newTimeData["200Array"], undefined, 4))
/*...
[
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
]
...*/
// PRETTY PRINTING ARRAY POINTED BY '404Array' key
console.log(JSON.stringify(newTimeData["404Array"], undefined, 4))
/*...
[
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
...*/
Output ยป
H:\RishikeshAgrawani\Projects\Sof\FilterArrays>node FilterArrays.js
{
"200Array": [
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
],
"404Array": [
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
}
[
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
]
[
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
I'm tried to convert javaScript array to JSON.
the javaScript array is full of details but the JSON is empty.
This is how I did the convert:
var jsonToDB = JSON.stringify(msgToDB);
I want to insert this array to mongoDB and because of this I did the convert to JSON.
This is how the array looks in debug (before the convert):
images: Array[1]
0: "vghbjn.jpg"
messageName: "ghjk"
millisecToShow: 1000
screenId: Array[1]
0: "screen1"
template: "Template1"
text: Array[1]
0: "vhbjnk"
timeFrame: Array[1]
0: Object
date: Object
end: "June 25, 2014"
start: "June 25, 2014"
days: Array[2]
0: "Sunday"
1: "Saturday"
time: Object
end: Object
hour: "23"
minutes: "00"
seconds: "0"
start: Object
hour: "00"
minutes: "00"
seconds: "0"
and the JSON is empty: jsonToDB: "[]".
I've modified my code with your original data, and it also worked fine. Don't know how you're getting the issue.
var msgToDB = {
"messageName": "1",
"text": [""],
"images": ["image1.jpg"],
"template": "template.html",
"millisecToShow": 100,
"timeFrame": [{
"date": {
"start": "January 1, 2014",
"end": "December 31, 2014"
},
"days": ["Sunday", "Saturday"],
"time": {
"start": {
"hour": "6",
"minutes": "0",
"seconds": "0"
},
"end": {
"hour": "7",
"minutes": "0",
"seconds": "0"
}
}
}],
"screenId": [1]
};
var jsonToDB = JSON.stringify(msgToDB);
console.log(jsonToDB);
And here is the JSFiddle link:- http://jsfiddle.net/Gk3e5/
Is any tool or online editor available so that it specify how to access a json element.For example if i provide json as input ,then we should get an output which will specify each item how can we access through javascript
Example
Assume Input is
var myList={ "vehicleList": { "Vehicle": [ { "vehicleId": 88, "vehicleName": "veh1", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1001, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1002, "AlertName": "Sudden acceleration", "Alertcount": 40 } ] }, { "vehicleId": 87, "vehicleName": "veh2", "totalEvents": 11, "medium": 4, "Severe": 7, "Category": [ { "AlertId": 1003, "AlertName": "Overspeed", "Alertcount": 30}, { "AlertId": 1004, "AlertName": "Drunk", "Alertcount": 10 } ] }, { "vehicleId": 87, "vehicleName": "veh3", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1007, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1008, "AlertName": "Overspeed", "Alertcount": 77 } ] }, { "vehicleId": 86, "vehicleName": "veh4", "totalEvents": 11, "medium": 4, "Severe": 5, "Category": [ { "AlertId": 1009, "AlertName": "Overspeed", "Alertcount": 17 }, { "AlertId": 1010, "AlertName": "HighSpeed", "Alertcount": 10 } ] } ] } };
Output should be a structure,which will specify like
myList.vehicleList.Vehicle[3].Severe;
It seems like you looking backward means providing the value you need what will be the expression to get the value. I don't have a solution for that.
But I would like to suggest json is very easy to read, may be you are having trouble due to long chunk of string. Try this website(editor) http://jsonlint.com/ this will validate your json and give you in more readable form. Hope this will help you in one or other way.