How to change data in a json response - javascript

I am getting a jsonResponse with some data like this:
[
{
"date":"2019-02-15",
"value":"5456"
},
{
"date":"2019-02-15",
"value":"5456"
},
{
"date":"2019-02-15",
"value":"5456"
},
{
"date":"2019-02-15",
"value":"-5456"
}
]
What I need is to change the delimiter in the date from " - " to " / ". I need date like: 2019/03/14
I tried to change them like this:
json.replace(/-/g, "/");
and it works but there is a problem. If for some reason the value data is negative -524. That minus will change also.
There si any way to change the delimiter without affecting another data ?
I need to keep the jsonResponse but with the delimiter change.

You have to loop through the array using Array.prototype.map and change the date :
const response = [
{
date: "2019-02-15",
value: "5456"
},
{
date: "2019-02-15",
value: "5456"
},
{
date: "2019-02-15",
value: "5456"
},
{
date: "2019-02-15",
value: "-5456"
}
];
const result = response.map(obj => ({ ...obj, date: obj.date.replace(/-/g, "/") }));
console.log(result);

Use Array.prototype.map to iterate over the objects in the array.
Format the date property by calling String.prototype.split("-") to split the date string it into an array using the - separator.
Then join the array using / by calling Array.prtotype.join("/"):
const data = [
{
"date":"2019-02-15",
"value":"5456"
},
{
"date":"2019-02-15",
"value":"5456"
},
{
"date":"2019-02-15",
"value":"5456"
},
{
"date":"2019-02-15",
"value":"-5456"
}
];
//This function does not modify the original object or the array
function formatDate(){
return data.map(o => ({...o, date: o.date.split("-").join("/")}));
}
console.log(formatDate(data));

you can try map
let response = json.map(doc => doc.date.replace(/-/g, "/"))

Related

JavaScript filter instead map

I have this code:
const uniform = {
zone: 'BOTTOM'
}
const sizes = [
{
_id: 'sizeId2',
zones: ['BOTTOM'],
value: '48'
},
{
_id: 'sizeId3',
zones: ['BOTTOM'],
value: '42'
},
]
sizes.map((size) => (size.zones.includes(uniform.zone) ? {
_id: size._id,
value: size.value,
} : null))
https://jsfiddle.net/pmiranda/945fsdw7/5/
// here I'm trying another way than map and the ternary
console.log(sizes.filter((size) => (size.zones.includes(uniform.zone) && {
_id: size._id,
value: size.value,
})))
I wonder, how could I replace that map with a filter? Because I think that mapping with a ternary with null could be done in a better way, plus, in the map way I'm getting that null in the end, I want to not add it to the array
I think that you'd filter then map:
sizes.filter(size => size.zones.includes(uniform.zone)).map(size => ({
_id: size._id,
value: size.value,
}));
You probably need to return the result, or assign it to a variable.
const uniform = { zone: 'BOTTOM' }
const sizes = [
{
_id: 'sizeId2',
zones: ['BOTTOM'],
value: '48'
},
{
_id: 'sizeId3',
zones: ['BOTTOM'],
value: '42'
},
]
// reduce
const newSizes = sizes.reduce((acc, size) =>
{
if(size.zones.includes(uniform.zone)) {
acc.push(
{
_id: size._id,
value: size.value
})
}
return acc;
}, []
)
console.log(newSizes);
Using either map or filter does not make sense in the cuurent usecase as you are not utilizing the return value.
If you need to just loop over the array and create new entries (containing or nnot containing null) you can use forEach or reduce.
From the "comments", reduce is more suitable for you.
Without map and filter, just create new array
let newSizes = [];
sizes.forEach(({zones, _id, value}, key) => zones.includes(uniform.zone) && (newSizes[key] = {_id, value}))

Print list of values from various arrays JavaScript

I am attempting to gather values from my API to input them into a graph. With that, I am looking to get an array of just the value 'date'. I have queried through the data to get the following printed:
That is through the following code:
return {
props: {
data: data
}
}
console.log([[props][0]['data']])
How do I simply get the 336 'date' values in an array? For example, [20210112, 20210111, 20210110...] I could not find any documentation to help with this issue, and I would appreciate any input.
You can map the data items and inside the callback, you can destructure the date field and return its value.
const data = [
{ date: 20210101 }, { date: 20210102 }, { date: 20210103 },
{ date: 20210104 }, { date: 20210104 }, { date: 20210105 }
];
const datesOnly = data.map(({ date }) => date);
console.log(datesOnly);
Destructuring can be simplified as:
const item = { date: 20210101 };
// Left-hand of assignment: Variables that match the field to be extracted
const { date } = item;
console.log(date);
The variables can also be renamed:
const item = { date: 20210101 };
const { date: myDate } = item;
console.log(myDate);
Update
If you want multiple field, you can map a new object.
const data = [
{ date: 20210101, eg: 1 }, { date: 20210102, eg: 2 }, { date: 20210103, eg: 3 },
{ date: 20210104, eg: 4 }, { date: 20210104, eg: 5 }, { date: 20210105, eg: 6 }
];
const datesEgsOnly = data.map(({ date }) => date);
const egsOnly = data.map(({ eg }) => eg);
const datesAndEgsOnly = data.map(({ date, eg }) => ({ date, eg }));
console.log(datesEgsOnly);
console.log(egsOnly);
console.log(datesAndEgsOnly);
.as-console-wrapper { top: 0; max-height: 100% !important; }

How to check if key of object in array has specific value in javascript

Is it possible to check if an object in an array has a specific Date value in the following data format?
I have an array like this for example
[
{
date: '2020-05-03',
items: [{}...]
},
...
]
-> In the above array, I want to check if any object in the array has '2020-05-03' as the date value.
And I want to find out if an object with Date is ??
I tried the following, but this only confirms that it has a 'date' as the key, and I couldn't compare values.
const existsDate = _.find(prev, 'date');
I also want to push an item to the items of the object containing that date if a date already exists.
If not, i need to create a new date object.
you caan use filter or find function
let arr = [
{data:'2020-05-23'},
{data:'2020-06-23'},
{data:'2020-07-23'}
]
let find = arr.find( (val) => val.data == '2020-06-23')
console.log(find)
You can make use of Array.prototype.find and do a string comparison
var arr = [
{
date: '2020-05-03',
items: [{}...]
},
]
const obj = arr.find(item => item.data === '2020-05-03');
EDIT: Since you want to update the existing array, you would need to make use of slice with findIndex to update array
var arr = [
{
date: '2020-05-03',
items: [{}...]
},
]
const newItem = {};
const index= arr.findIndex(item => item.data === '2020-05-03');
if(index > -1) {
arr = [...arr.slice(0, index), {...arr[index], items: arr[index].items.concat(newItems), ...arr.slice(index + 1)}
} else {
arr.push({data: new Date(), items: [newItem]})
}
You can use, Array find(), some() to get/check the required conditions, for example:
const arr = [
{
date: '2020-05-03',
items: [{}]
},
{
date: '2020-05-02',
items: [{}]
}
]
function checkAndAdd(date) {
const res = arr.find(ob => ob.date === date);
// console.log(res);
// based on the added comments.
// if date is found, push something to the items, list:
if (res) {
res.items.push('Hello');
} else {
arr.push({
date,
items: [{}]
})
}
console.log('finalArray', arr);
}
checkAndAdd('2020-05-03');
checkAndAdd('2020-05-06');
I'm not sure what exactly you are looking to do but his code iterates through the array of objects and checks against the date variable. It outputs the index (i).
let date = "2020-05-03"
const array = [
{ date: "2020-05-01" },
{ date: "2020-05-02" },
{ date: "2020-05-03", },
]
for(let i = 0 ; i < array.length ; i ++) {
if(array[i].date === date) {
console.log(i); }
else {
console.log("Date not in array");
}
}

How can I format my array of objects in javascript?

Need to format my array of objects to have a nested object.
Tried using map, and reduce. Can't seem to get the formatting correct.
Currently getting this.
[
{
"date": "2019-10-01T00:00:00Z",
"total": 20
}
]
Need it to be in this format.
[
{
name: 'Total Call Volume',
data: {
'2019-01-01 00:00:00 -0800': 0,
'2019-01-01 00:00:00 -0800': 88,
}
}
]
var arr = this.$store.state.aggregatedCallVolumeData;
var mapData = arr.map(item => ({
date: item.startTime,
total: item.dataValues.TOTAL_CALL_VOLUME
}));
var data = mapData.reduce((acc, value) => {
acc[value.date] = acc[value.date] ? acc[value.date] : [];
acc[value.date] ? acc[value.date].push(value.total) : [value.total];
return acc;
}, {});
let result = Object.entries(data).map(d => ({ id: d[0] + ':' + d[1] }) );
console.log(result)
console output is
0: {id: "2019-10-27T00:00:00Z:0"}
1: {id: "2019-10-28T00:00:00Z:88"}
arr.reduce((obj, item) => {
obj.data[item.date] = item.total;
return obj;
}, {
name: 'Total Call Volume',
data: {}
})
something like that. You might need to switch around the 'obj' and 'item' param. Basically the obj param is the second argument in the reduce function. So the obj is that base object I added at the end, and the 'item' param is each item in the array. So we loop and keep adding the values on to the 'obj' and return it for the next loop to add onto

Format Json, remove duplicates and count elements in javascript

I'm a little lost, I have a dataset in json format with timestamps and ids like this:
[{
"date":"2016-11-18 19:20:42","id_pa":"7"
},{
"date":"2016-11-18 19:04:55","id_pa":"5"
},{
"date":"2016-11-19 20:53:42","id_pa":"7"
},{
"date":"2016-11-19 20:53:43","id_pa":"7"
},{
"date":"2016-11-19 20:53:43","id_pa":"7"
},{
"date":"2016-11-20 20:49:42","id_pa":"7"
},{
"date":"2016-11-20 20:50:45","id_pa":"7"
},{
"date":"2016-11-20 20:50:46","id_pa":"7"
}]
And I want to build a json that displays the date and the number of IDs each day. The new Json would be like this:
[{
"date":"18-11-2016","num_pa":"2"
},{
"date":"19-11-2016","num_pa":"1"
},{
"date":"20-11-2016","num_pa":"1"
}]
I figured I had to do a .map to format the date so it shows dd-mm-yyyy, then a .filter to remove duplicates and finally a .reduce to count the diferent ids for every date. So far I've done only the .map procedure but I'm not sure how to do the next steps and either my solution is the best solution or not.
This is a piece of my code:
SwapSvc
.getUsage (vm.id_fi)
.then((data)=>{
//console.log(`lreceived data: `+ JSON.stringify(data) );
vm.fdata = data.map((elem) => {
//console.log(`date: ${elem.date}`);
//console.log(`id_pa: ${elem.id_pa}`);
var d = new Date (elem.date);
return{
date:d.getDate()+'-'+d.getMonth()+'-'+d.getFullYear()/*elem.date*/,
id_pa:elem.id_pa
}})
var temp = [];
vm.filteredData = vm.fdata.filter((elem, index) => {
if(temp.indexOf(elem.date)<0){
temp.push(elem);
return true;
}
else return false;
});
console.log(`data after parsing and ordering: `+ JSON.stringify(vm.filteredData) );
return data;
})
.catch((err)=>{
//error
console.log(`error, no response`);
throw err;
});
PS: I'm using angular 1.6 with ES6.
Thanks in advance
BRJ
You could use a hash table for the date and collect all id_pa for later count.
var data = [{ date: "2016-11-18 19:20:42", id_pa: "7" }, { date: "2016-11-18 19:04:55", id_pa: "5" }, { date: "2016-11-19 20:53:42", id_pa: "7" }, { date: "2016-11-19 20:53:43", id_pa: "7" }, { date: "2016-11-19 20:53:43", id_pa: "7" }, { date: "2016-11-20 20:49:42", id_pa: "7" }, { date: "2016-11-20 20:50:45", id_pa: "7" }, { date: "2016-11-20 20:50:46", id_pa: "7" }],
hash = Object.create(null),
result;
data.forEach(function (a) {
var date = a.date.slice(0, 10);
hash[date] = hash[date] || Object.create(null);
hash[date][a.id_pa] = true;
});
result = Object.keys(hash).map(date => ({ date, num_pa: Object.keys(hash[date]).length }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can just chain reduce onto your map call and use the ES6 findIndex method to see if the object currently exists within the array being created by the reduce function.
SwapSvc
.getUsage (vm.id_fi)
.then((data)=>{
//console.log(`lreceived data: `+ JSON.stringify(data) );
vm.fdata = data.map((elem) => {
//console.log(`date: ${elem.date}`);
//console.log(`id_pa: ${elem.id_pa}`);
var d = new Date (elem.date);
return{
date:d.getDate()+'-'+d.getMonth()+'-'+d.getFullYear()/*elem.date*/,
id_pa:elem.id_pa
}}).reduce((p, c, i) => {
var index = p.findIndex(x => x.date === c.date);
if (index !== -1) p[index].num_pa++;
else p.push({"date": c.date, "num_pa": 1})
return p;
}, [])
console.log(`data after parsing and ordering: `+ JSON.stringify(vm.fData) );
return data;
})

Categories