Getting dates from JSON for D3 - javascript

My JSON file has the dates separated like this:
"time": {
"date": {
"year": 2018,
"month": 2,
"day": 25
},
"time": {
"hour": 10,
"minute": 19,
"second": 6,
"nano": 19000000
}
},
The tutorial I used to get a line graph in d3 going was in this link:
https://datawanderings.com/2019/10/28/tutorial-making-a-line-chart-in-d3-js-v-5/
Using the code below:-
const timeConv = d3.timeParse("%d-%b-%Y");
const dataset = d3.csv(datacsv);
dataset.then(function(data) {
var slices = data.columns.slice(1).map(function(id) {
return {
id: id,
values: data.map(function(d){
return {
date: timeConv(d.date),
measurement: +d[id]
};
})
};
});
});
How could I use the same code but use the JSON file with the separated date values?

Just make up the actual date string from the separate dates:
return {
date: timeConv(d.time.date.day + '-' + d.time.date.month + '-' + d.time.date.year),
measurement: +d[id]
};
Since the month is not described as the abbreviated month name, you need to change timeConv as
const timeConv = d3.timeParse("%d-%m-%Y");
An json data example:
let dataset = [{
"id": 1,
"time": {
"date": {
"year": 2018,
"month": 2,
"day": 25
},
"time": {
"hour": 10,
"minute": 19,
"second": 6,
"nano": 19000000
}
}
}, {
"id": 2,
"time": {
"date": {
"year": 2019,
"month": 2,
"day": 25
},
"time": {
"hour": 10,
"minute": 19,
"second": 6,
"nano": 19000000
}
}
}]
const timeConv = d3.timeParse("%d-%m-%Y");
newData = dataset.map(function(d) {
return {
date: timeConv(d.time.date.day + '-' + d.time.date.month + '-' + d.time.date.year),
measurement: +d.id
}
})
console.log(newData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Related

Merge specific array values into single value

I have parsed a csv file which gives me an array like this:
[{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
},
{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
}]
I want to merge minute,hour,day,month,year to a single key. Like this:
"time": "2019-07-02 09:57:35"
so i can use this as a datetime object on my API.
The way I am currently getting data is:
const cleanKeys = [
'year',
'month',
'day',
'hour',
'minute',
'temperature',
];
const dataAsObject = totalData.map(function (values) {
return cleanKeys.reduce(function (o, k, i) {
o[k] = values[i];
return o;
}, {})
});
This is basically adding a header key to all data. I am only interested in merging minute, hour, day, month, year column.
I suggest you to use built in Date constructor:
var obj = {"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52};
const date = new Date(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute);
const newObj = {date, temperature: obj.temperature};
console.log(JSON.stringify(newObj));
EDIT:
please find below updated answer using date in loop:
const arr = [{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
},
{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
}];
const newArr = arr.reduce((a,c) => {
const date = new Date(c.year, c.month - 1, c.day, c.hour, c.minute);
a.push({date, temperature: c.temperature});
return a;
}, []);
console.log(JSON.stringify(newArr));
You can create the string yourself, e.g.:
yourArray["time"] = `${yourArray.year}-${yourArray.month}-${yourArray.day} ${yourArray.hours}:${yourArray.minutes}:${yourArray.seconds}`;

Keys problems when mapping using Lodash

I am trying to get my monthly sales and put them on the chart. They're going to be grouped by year. This is what I've done so far:
let result = _
.chain(res.data)
.groupBy("_id.year")
.value();
result = _.map(result, (yearlyValues, key) => {
return {
[key]: _.map(yearlyValues, yearlyValuesItems => {
return {
[yearlyValuesItems._id.month]: yearlyValuesItems.count
};
})
};
});
result = _.map(result, (value, key) => {
return _.map(value, (innerValues, innerKey) => {
return innerValues;
})
})
result = _.flatten(result);
result = _.map(result, (value, key) => {
return _.map(value, (items, keys) => {
return _.map(items, (a, b) => {
return a
})
})
});
for (var i in result) {
final_count.push(_.flatten(result[i]));
}
console.log(final_count);
$scope.labels_monthly = monthNames;
$scope.series = Object.keys(final_count);
$scope.data = Object.values(final_count);
$scope.options = {
legend: {
display: true
}
};
My data: https://pastebin.com/WhJ0atTX
My output: https://jsfiddle.net/asfxtor4/1/
My problem is that I am getting keys 0, 1, 2 instead of 2016, 2017, 2018.
And then inside I need to get key as a month number.This key has to be 2 because the month is March, but it generates 0. You can see in the pictures.
This is my desired output: https://pastebin.com/iChhrnNG, I need to get an array of all months and if there is data for just March lets say, all other array elements should be 0.
You can get an array of objects with years and values by adding 'entries' e.g.
let result = _
.chain(data)
.groupBy("_id.year")
.entries()
.value()
.map((item) => ({year: item[0], values: item[1]}));
You then won't need:
result = _.map(result, (yearlyValues, key) => {
return {
[key]: _.map(yearlyValues, yearlyValuesItems => {
return {
[yearlyValuesItems._id.month]: yearlyValuesItems.count
};
})
};
});
You can see a fiddle here:
https://jsfiddle.net/Fresh/yr8bqteL/
Hopefully this info will help you complete this assignment.
Since you know you always have 12 months you could be somewhat less fancy and do this:
data = [{
"_id": {
"month": 12,
"year": 2018
},
"count": 3
},
{
"_id": {
"month": 11,
"year": 2018
},
"count": 4
},
{
"_id": {
"month": 9,
"year": 2018
},
"count": 3
},
{
"_id": {
"month": 8,
"year": 2018
},
"count": 4
},
{
"_id": {
"month": 5,
"year": 2018
},
"count": 4
},
{
"_id": {
"month": 7,
"year": 2018
},
"count": 2
},
{
"_id": {
"month": 4,
"year": 2018
},
"count": 5
},
{
"_id": {
"month": 9,
"year": 2017
},
"count": 2
},
{
"_id": {
"month": 8,
"year": 2017
},
"count": 4
},
{
"_id": {
"month": 11,
"year": 2017
},
"count": 4
},
{
"_id": {
"month": 10,
"year": 2017
},
"count": 3
},
{
"_id": {
"month": 4,
"year": 2017
},
"count": 2
},
{
"_id": {
"month": 2,
"year": 2017
},
"count": 3
},
{
"_id": {
"month": 6,
"year": 2017
},
"count": 1
},
{
"_id": {
"month": 1,
"year": 2018
},
"count": 4
},
{
"_id": {
"month": 2,
"year": 2018
},
"count": 4
},
{
"_id": {
"month": 3,
"year": 2018
},
"count": 9
},
{
"_id": {
"month": 10,
"year": 2018
},
"count": 3
},
{
"_id": {
"month": 3,
"year": 2017
},
"count": 9
},
{
"_id": {
"month": 7,
"year": 2017
},
"count": 2
},
{
"_id": {
"month": 12,
"year": 2017
},
"count": 3
},
{
"_id": {
"month": 3,
"year": 2016
},
"count": 1
},
{
"_id": {
"month": 1,
"year": 2017
},
"count": 3
},
{
"_id": {
"month": 6,
"year": 2018
},
"count": 3
}
]
let result = _
.chain(data)
.groupBy("_id.year")
.reduce((obj, current, index) => {
var sortedMonths = _.sortBy(current, (v) => v._id.month), monthsArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
_.map(current, (curObj, i) => monthsArray[_.get(sortedMonths, '[' + i + ']._id.month') - 1] = sortedMonths[i].count)
return _.extend(obj, { [index]: monthsArray })
}, {})
.value();
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Push data to array without using if statement

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
}
]

JavaScript - iterate over object

I have an object like this that I get from an external endpoint so cannot change:
let obj = {
0: { "time": 1, "day": 1, },
1: { "time": 2, "day": 1, },
2: { "time": 3, "day": 1, },
3: { "time": 1, "day": 2, },
4: { "time": 2, "day": 2, },
5: { "time": 3, "day": 2, }
}
I need to get it into a format like:
1: {
1: { "time": 1, "day": 1 },
2: { "time": 2, "day": 1 },
3: { "time": 3, "day": 1 },
},
2: {
1: { "time": 1, "day": 2 },
2: { "time": 2, "day": 2 },
3: { "time": 3, "day": 2 },
}
Where the first key is the day, and the second is the time.
My attempt doesn't work
let obj = {
0: { "time": 1, "day": 1, },
1: { "time": 2, "day": 1, },
2: { "time": 3, "day": 1, },
3: { "time": 1, "day": 2, },
4: { "time": 2, "day": 2, },
5: { "time": 3, "day": 2, }
}
let test = {}
let defaultRow = {
1: {},
2: {}
}
Object.keys(obj).forEach((key) => {
if (!test[obj[key]["day"]]) {test[obj[key]["day"]] = defaultRow}
test[obj[key]["day"]][obj[key]["time"]] = obj[key]
})
console.log(test)
Both days contain the same data for some reason. How can I achieve this? Any help is appreciated!
Both days contain the same data for some reason
Because you assign the same object reference defaultRow to each row. A simple fix is turn defaultRow into a function that returns a new object each time
let obj = {
0: { "time": 1, "day": 1, },
1: { "time": 2, "day": 1, },
2: { "time": 3, "day": 1, },
3: { "time": 1, "day": 2, },
4: { "time": 2, "day": 2, },
5: { "time": 3, "day": 2, }
}
let test = {}
let defaultRow = function() {
return {
1: {},
2: {}
}
}
Object.keys(obj).forEach((key) => {
if (!test[obj[key]["day"]]) {
test[obj[key]["day"]] = defaultRow();
}
test[obj[key]["day"]][obj[key]["time"]] = obj[key]
})
console.log(test)
Simple example of the problem
var obj ={a:1},
foo = obj,
bar = obj;
foo.a=2;
console.log(bar.a) //returns 2 because is same object as foo
You could take the objects and build a new object with a new structure.
var object = { 0: { time: 1, day: 1 }, 1: { time: 2, day: 1 }, 2: { time: 3, day: 1 }, 3: { time: 1, day: 2 }, 4: { time: 2, day: 2 }, 5: { time: 3, day: 2 } },
result = Object.values(object).reduce(
(r, o) => ((r[o.day] = r[o.day] || {})[o.time] = o, r),
{}
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Convert into an array of object using Object#values, and iterate the array using Array#reduce to convert to the desired format.
const obj = {"0":{"time":1,"day":1},"1":{"time":2,"day":1},"2":{"time":3,"day":1},"3":{"time":1,"day":2},"4":{"time":2,"day":2},"5":{"time":3,"day":2}};
const result = Object.values(obj).reduce((r, o) => {
r[o.day] = Object.assign(r[o.day] || {}, { [o.time]: o });
return r;
}, {});
console.log(result);
Since you want your nested objects to be plain objects not arrays the solution to get last index is rather involved.
let obj = {
0: { "time": 1, "day": 1, },
1: { "time": 2, "day": 1, },
2: { "time": 3, "day": 1, },
3: { "time": 1, "day": 2, },
4: { "time": 2, "day": 2, },
5: { "time": 3, "day": 2, }
}
console.log(
Object.values(obj).reduce(
(acc, value) => {
const holder = acc[value.day] || (acc[value.day] = { })
const keys = Object.keys(holder).map(key => +key)
holder[keys.length ? (Math.max(...keys) + 1) : 1] = value
return acc
},
{}
)
)
To solve this problem, you need to iterate through your object and make value of day as your outer and increment the inner key as per the number of keys in the Object which you can get by Object.keys.length.
Here is the sample code.
let obj = {
0: {
"time": 1,
"day": 1,
},
1: {
"time": 2,
"day": 1,
},
2: {
"time": 3,
"day": 1,
},
3: {
"time": 1,
"day": 2,
},
4: {
"time": 2,
"day": 2,
},
5: {
"time": 3,
"day": 2,
}
}
let newObj = {};
for (let key in obj) {
if(typeof newObj[obj[key]["day"]] !== "object") {
newObj[obj[key]["day"]] = {};
}
let index = Object.keys(newObj[obj[key]["day"]]).length + 1;
newObj[obj[key]["day"]][index] = obj[key];
}
console.log(newObj);
This will work for you
var result = Object.values(obj).reduce((count, currentValue) => {
count[currentValue.day] = count[currentValue.day] || {};
count[currentValue.day][Object.keys(count[currentValue.day]).length + 1] = currentValue;
return count
}, {});
There is start with :
const result = Object.values(obj).reduce((accumulator, currentValue) => {
if (!accumulator[currentValue.day]) accumulator[currentValue.day] = []
accumulator[currentValue.day].push(currentValue)
return accumulator
}, {})
console.log(result)
This is not THE solution but a starting kit :)
More infos:
- MDN reduce
- Stackoverflow search
// your code goes here
let obj = {
0: { "time": 1, "day": 1, },
1: { "time": 2, "day": 1, },
2: { "time": 3, "day": 1, },
3: { "time": 1, "day": 2, },
4: { "time": 2, "day": 2, },
5: { "time": 3, "day": 2, }
}
obj = Object.values(obj).reduce(function(newObject, val){
//console.log(val.day, val.time, newObject);
if(newObject[val['day']] == undefined)
newObject[val['day']] ={};
newObject[val['day']][val['time']] = val;
//console.log(val.day, val.time, newObject);
return newObject;
},{})
console.log(obj);
/*
output
{ '1':
{ '1': { time: 1, day: 1 },
'2': { time: 2, day: 1 },
'3': { time: 3, day: 1 } },
'2':
{ '1': { time: 1, day: 2 },
'2': { time: 2, day: 2 },
'3': { time: 3, day: 2 } } }
*/
I don't really know why you need an object with properties 1...n instead of just using arrays for this purpose. I would solve it like this:
let obj = {
0: { "time": 1, "day": 1, },
1: { "time": 2, "day": 1, },
2: { "time": 3, "day": 1, },
3: { "time": 1, "day": 2, },
4: { "time": 2, "day": 2, },
5: { "time": 3, "day": 2, }
};
function orderByDay(obj){
const result = {};
Object.keys(obj).forEach(function(key){
let day = obj[key].day;
if(result.hasOwnProperty(day)){
result[day].push(obj[key]);
}else{
result[day] = [obj[key]];
}
});
return result;
}
console.log(orderByDay(obj));
My rather readable version
let obj = {
0: { "time": 1, "day": 1, },
1: { "time": 2, "day": 1, },
2: { "time": 3, "day": 1, },
3: { "time": 1, "day": 2, },
4: { "time": 2, "day": 2, },
5: { "time": 3, "day": 2, }
}
let test = {}
for (let o in obj) {
const day = obj[o].day;
const time = obj[o].time;
if (test[day]==undefined) {
test[day] = {}
}
test[day][time] = {day:day,time:time}
}
console.log(test)

Get specific values of nested object within array

I make an AJAX request and I receive this (looking at the Network tab)
[
{
"request": "Amount of rainfall by day",
"days": [
{
"day": 1,
"amount": 50
}, {
"day": 2,
"amount": 10
}, {
"day": 3,
"amount": 10
}, {
"day": 4,
"amount": 150
}, {
"day": 5,
"amount": 130
}, {
"day": 6,
"amount": 45
}, {
"day": 7,
"amount": 10
}
]
}
]
I would like to create an array with the values of 'amount'.
[50,10,10,150,130,45,10]
(the order is important; I will show these values in a chart with chronological order)
I tried lodash.values as well as for..in but the mix between nested arrays and nested objects is rather confusing.
I would like an elegant solution.
Question 1: Should I use a Json method to remove the outside root level array ? Any way to get rid of it?
Question 2: Which data structure should I use in order to keep the relation between days and amounts? (my charting library, Chart.js receives a simple array of single values.
Use Array#map to create a new array from the requested values:
var data = [{"request":"Amount of rainfall by day","days":[{"day":1,"amount":50},{"day":2,"amount":10},{"day":3,"amount":10},{"day":4,"amount":150},{"day":5,"amount":130},{"day":6,"amount":45},{"day":7,"amount":10}]}];
var result = data[0].days.map(function(obj) {
return obj.amount;
});
console.log(result);
Question 1
You can tranverse it easily by using data[0], and after you'll map / reduce, you'll get a new data structure.
Question 2
You can use a simple object, with two related arrays by using Array#reduce:
var data = [{"request":"Amount of rainfall by day","days":[{"day":1,"amount":50},{"day":2,"amount":10},{"day":3,"amount":10},{"day":4,"amount":150},{"day":5,"amount":130},{"day":6,"amount":45},{"day":7,"amount":10}]}];
var result = data[0].days.reduce(function(r, o) {
r.days.push(o.day);
r.amounts.push(o.amount);
return r;
}, { days: [], amounts: [] });
console.log(JSON.stringify(result));
I use the Lodash to answer your question
var response = [
{
"request": "Amount of rainfall by day",
"days": [
{
"day": 1,
"amount": 50
}, {
"day": 2,
"amount": 10
}, {
"day": 3,
"amount": 10
}, {
"day": 4,
"amount": 150
}, {
"day": 5,
"amount": 130
}, {
"day": 6,
"amount": 45
}, {
"day": 7,
"amount": 10
}
]
}
];
// using _.map function
_.map(response[0].days, 'amount');
Lodash
Use this:
var reply = [
{
"request": "Amount of rainfall by day",
"days": [
{
"day": 1,
"amount": 50
}, {
"day": 2,
"amount": 10
}, {
"day": 3,
"amount": 10
}, {
"day": 4,
"amount": 150
}, {
"day": 5,
"amount": 130
}, {
"day": 6,
"amount": 45
}, {
"day": 7,
"amount": 10
}
]
}
];
var amounts = reply[0].days.map((i) => { return i.amount });
console.log(amounts);
In case the day property value does not follow the order of the elements in the response object, you may need to use that value as index in your final array. Here is an ES6 solution:
var response = [
{
"request": "Amount of rainfall by day",
"days": [
{
"day": 1,
"amount": 50
}, {
"day": 2,
"amount": 10
}, {
"day": 3,
"amount": 10
}, {
"day": 4,
"amount": 150
}, {
"day": 5,
"amount": 130
}, {
"day": 6,
"amount": 45
}, {
"day": 7,
"amount": 10
}
]
}
];
var arr = response[0].days.reduce( (arr, o) => (arr[o.day-1] = o.amount, arr), []);
console.log(arr);
So this would even work if the value for day 4 were missing. The value at the corresponding index in the output array (index 3) would have undefined in that case.

Categories

Resources