Print list of values from various arrays JavaScript - 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; }

Related

remove object from array using an id before saving it in local storage in react native

I am saving few data as an object in array in my local storage using AsyncStorage, I am able to do it in following way:
const [saveData, setSaveData] = useState([]);
useEffect(() => {
AsyncStorage.setItem('test4', JSON.stringify(saveData))
.then(json => console.log('success!'))
.catch(error => console.log('error!'));
}, [saveData]);
const _submitWithWeather = async text => {
let date = new Date();
const curDate = moment(date).format('MMM DD');
let newItem;
newItem = {
id: curDate,
date: curDate,
description: text,
imageURL: photo,
location: getLocation,
temperature: getWeather,
weatherType: geType,
};
setSaveData(prevList => {
prevList = prevList || [];
if (prevList.length < 0) {
return newItem;
} else {
return [...prevList, newItem];
}
});
};
<TouchableOpacity
onPress={() => {
_submitWithWeather(text);
}}>
<Text>save</Text>
</TouchableOpacity>
I am passing today's date as an id, because if the date on which I am saving my data, matches an object with same date then it should replace the object from array whose date is also today's data.
for example:
[
{
"date": "Jan 02",
"description": "1",
"id": "Jan 02",
"imageURL": "urlImage.jpg",
"location": "location",
"temperature": "13°C",
"weatherType": "Clear"
}
]
today's date is jan 02, and if I change the description or image and then click save , then this new object should replace the older object whose date is also jan 02
You can achieve this by using Array.filter to filter out based on your Id prop and spread operator to bring it back together.
const d1 = [
{
date: 'Jan 01',
description: '1',
},
{
date: 'Jan 02',
description: '2',
},
];
const d2 = {
date: 'Jan 01',
description: 'abc',
};
const getData = () => {
const d1WithoutDateToUpdate = d1.filter((d) => d.date != d2.date);
const updatedD1 = [...d1WithoutDateToUpdate, d2];
return updatedD1;
};
You could do a simple Array#map to update the data.
setSaveData(prevList => {
if (prevList.length) {
return prevList.map(obj => (newItem.date === obj.date) ? newItem : obj);
}
return [newItem]
});
As you've already initialized the value you don't need to set prevList = prevList || []

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 to get unique date values from object array

I need to get all unique days of multiple date values in the format DD.MM.. In this example data, there are two values for the 24th of december:
const data = [
{ date: ISODate("2019-12-24T03:24:00Z") },
{ date: ISODate("2019-12-24T04:56:00Z") },
{ date: ISODate("2019-12-25T02:34:00Z") },
{ date: ISODate("2019-12-26T01:23:00Z") }
]
So the result should be
const result = [
'24.12.',
'25.12.',
'26.12.'
]
So first of all I'll map my data and split the values only for the dates:
const dates = data.map(d => d.date.toString().split('T')[0])
But how do I get the unique values and change the output format?
Update
I came up with this, but it looks very complicated...
data.map(d => {
const dateSplit = d.date.toString().split('T')[0].split('-')
return dateSplit[2] + '.' + dateSplit[1] + '.'
})
.filter((value, index, self) {
return self.indexOf(value) === index
})
It seems that ISODate returns a standard JS Date object. You can use Date.getDate() to get the day, and Date.getMonth() to get the month (0 based, so we need to add 1):
const data = [
{ date: new Date('2019-12-24T03:24:00Z') },
{ date: new Date('2019-12-24T04:56:00Z') },
{ date: new Date('2019-12-25T02:34:00Z') },
{ date: new Date('2019-12-26T01:23:00Z') }
]
const result = [...new Set(data.map(({ date: d }) =>
`${d.getDate()}.${d.getMonth() + 1}.`
))]
console.log(result)
Previous answer:
Use a regular expression to match the month and the day, and assign them to consts using destructuring. Assemble the string using template literal. Remove duplicates by assigning the values to a Set, and then spreading back to an array.
Note: Since I don't have access to the ISODate, I've removed it. I left .toString() although it's not needed in this example, but will be needed when used with ISODate.
const data = [
{ date: '2019-12-24T03:24:00Z' },
{ date: '2019-12-24T04:56:00Z' },
{ date: '2019-12-25T02:34:00Z' },
{ date: '2019-12-26T01:23:00Z' }
]
const pattern = /-([0-9]{2})-([0-9]{2})T/
const result = [...new Set(data.map(d => {
const [, mon, day] = d.date.toString().match(pattern)
return `${day}.${mon}.`;
}))]
console.log(result)
Use .filter() to filter through only values that are the first of their value.
//temporary function
const ISODate = (d) => d;
const data = [{
date: ISODate("2019-12-24T03:24:00Z")
},
{
date: ISODate("2019-12-24T04:56:00Z")
},
{
date: ISODate("2019-12-25T02:34:00Z")
},
{
date: ISODate("2019-12-26T01:23:00Z")
}
]
const dates = data.map(d => d.date.toString().split('T')[0].split("-").slice(1, 3).reverse().join(".") + ".")
console.log(dates.filter((v, i, a) => a.indexOf(v) === i));
You can do this pretty easily by using Array.reduce. Note that I converted ISODate to be Date since I don't have that class, but it should be the same concept.
const data = [
{ date: new Date("2019-12-24T03:24:00Z") },
{ date: new Date("2019-12-24T04:56:00Z") },
{ date: new Date("2019-12-25T02:34:00Z") },
{ date: new Date("2019-12-26T01:23:00Z") }
];
const result = data.reduce( (acc, curr) => {
if (acc.length > 0) {
const hasDate = acc.find(d => d.date.getMonth() === curr.date.getMonth() && d.date.getDate() === curr.date.getDate());
if (!hasDate) { acc.push(curr); }
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(result);
I would use the uniq function in the Underscore.js library:
const data = [
{ date: ISODate("2019-12-24T03:24:00Z") },
{ date: ISODate("2019-12-24T04:56:00Z") },
{ date: ISODate("2019-12-25T02:34:00Z") },
{ date: ISODate("2019-12-26T01:23:00Z") }
];
let dates = _.uniq(data.map(d => d.date.toString().split('T')[0]));
A nice considerable way is:
const array = [1, 2, 6, 5,5, 5, 3, 7, 8];
const uniqueKeys = array.reduce((hashMap, value) => {
if (!hashMap[value]) {
hashMap[value] = true;
}
return hashMap;
}, {});
const uniqueValues = Object.keys(uniqueKeys);
console.log(uniqueValues);
It is nice because it iterates the array once, instead of x * x (a.k.a log(n) instead of log(n^2) as with .filter() example
const array = [1, 2, 6, 5,5, 5, 3, 7, 8];
const uniqueKeys = array.reduce((hashMap, value) => {
if (!hashMap[value]) {
hashMap[value] = true;
}
return hashMap;
}, {});
const uniqueValues = Object.keys(uniqueKeys);
console.log(uniqueValues);

How to change data in a json response

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, "/"))

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