Array .map() returning undefined - arrays

This is the structure of the array when I console.log it.
-[]
-0: Array(31)
-0:
-date: "2018-08-26T00:00:00-04:00"
-registered:
-standard: 0
-vip: 0
-waitlisted:
-standard: 0
-vip: 0
This is my code to map the date and the registered (two separate arrays):
this.data.map((value) => value.date);
this.data.map((value) => value.registered['standard']);
I either get an empty array or undefined when I log these. What am I doing wrong?
I want to use these for a chart using ChartJS where:
this.lineChart = new Chart(lineCtx, {
type: 'line',
data: {
datasets: [{
label: (I want the dates to be the labels),
data: (I want the list of standard registrants)
}]...
EDIT:
I've updated the way I get the data to show the following structure:
{
"registrationHistory": [{
"date": "2018-08-26T00:00:00-4:00",
"registered": {
"vip":0,
"standard":0
},
"waitlisted":{
"vip":0,
"standard":0
}
{
,...
}
]}

Your array is two-dimensional and map is iterating only the first dimension, i.e:
-[]
-0: Array(31) // first dimension
-0: // second dimension
-date: "2018-08-26T00:00:00-04:00"
...
This would look like the following JSON string:
[[{"date":"2018-08-26T00:00:00-04:00", ...}]]
Since you haven't provided a full example it's impossible to recommend the most applicable solution:
If you control the data source, remove the first dimension since it appears redundant.
Assuming you only want the first element of the first dimension, refer to that key:
this.data[0].map((value) => value.date);
If your data model is more complex than revealed in your question you'll need to figure out another approach.

Related

How to pull all objects from an array of unknown length and place them into a state variable in React?

I imported data from another file (so I technically think it's an object containing an array of objects) called { groupData }. At the moment, the array contains only 5 objects, but it is variable in length and could contain more. Each object looks like this:
{
name: "A Name",
img: "https://imgURL.goes.here",
details: "This is a fun group about fun things.",
likes: 45,
},
My goal is to take each object from the array, modify the data, and place the objects into an empty stateful array called "groups". I want each object to look like this before it goes into the new "groups" array:
{
name: "A Name",
img: "https://imgURL.goes.here",
details: "This is a fun group about fun things.",
hasNotification: Boolean,
userIsAdmin: Boolean,
},
I thought of destructuring the array, but this solution is not scalable if things are going to be added to the array:
const [groupZero, groupOne, groupTwo, groupThree, groupFour] = groupData;
What is the most efficient way to accomplish this? Thank you!!
I am not exactly sure what you need because of the lack of context. But you can use a for loop to iterate through each object in the array.
If it is fine to moderate the existing data:
for (data of groupData){
delete data.likes;
data.hasNotification = true; // or false
data.userIsAdmin = true; // or false
}
setState(groupData); // if you are using useState hooks
If you do not want to change original data:
// create a deep clone of groupData
const newGroup = JSON.parse(JSON.stringify(groupData));
for (data of newGroup){
delete data.likes;
data.hasNotification = true; // or false
data.userIsAdmin = true; // or false
}
setState(newGroup);
Adjust the setState section accordingly if you are using class components

Importing JSON that starts with an array

I am trying to use excel to import and show a JSON. I've got this working for most JSONs. With this particular JSON, it starts with an array and I don't know how the parseOptions syntax to address and array first and then objects.I have successfully used =IMPORTJSON("url", "object to call") I want to display the '[0]/metadata/last_name' for each array object.
here is my code:
=IMPORTJSON("https://api.sleeper.app/v1/draft/547633764530618368/picks","[0]/metadata/last_name")
Here is my JSON:
[
{
"round":1,
"roster_id":null,
"player_id":"4866",
"picked_by":"448639868432543744",
"pick_no":1,
"metadata":{
"years_exp":"2",
"team":"NYG",
"status":"Active",
"sport":"nfl",
"position":"RB",
"player_id":"4866",
"number":"26",
"news_updated":"1577679319834",
"last_name":"Barkley",
"injury_status":"",
"first_name":"Saquon"
},
"is_keeper":null,
"draft_slot":1,
"draft_id":"547633764530618368"
},
{
"round":1,
"roster_id":null,
"player_id":"4046",
"picked_by":"341432375512702976",
"pick_no":2,
"metadata":{
"years_exp":"3",
"team":"KC",
"status":"Active",
"sport":"nfl",
"position":"QB",
"player_id":"4046",
"number":"15",
"news_updated":"1583891151374",
"last_name":"Mahomes",
"injury_status":"",
"first_name":"Patrick"
},
"is_keeper":null,
"draft_slot":2,
"draft_id":"547633764530618368"
},
{
"round":1,
"roster_id":null,
"player_id":"4881",
"picked_by":"539512871341760512",
"pick_no":3,
"metadata":{
"years_exp":"2",
"team":"BAL",
"status":"Active",
"sport":"nfl",
"position":"QB",
"player_id":"4881",
"number":"8",
"news_updated":"1580608524794",
"last_name":"Jackson",
"injury_status":"Probable",
"first_name":"Lamar"
},
"is_keeper":null,
"draft_slot":3,
"draft_id":"547633764530618368"
}
Okay, I figured the first part out. code looks like this:
\\
=IMPORTJSON("https://api.sleeper.app/v1/draft/547633764530618368/picks","0/metadata/first_name")
\\
But now I'm trying to have the cells run through a FOR Loop of the array. So it starts at 0 (as in 0/metadata/first_name), but how do I set it in a loop so that each cell increased the array number?

Using $rename in MongoDB for an item inside an array of objects

Consider the following MongoDB collection of a few thousand Objects:
{
_id: ObjectId("xxx")
FM_ID: "123"
Meter_Readings: Array
0: Object
Date: 2011-10-07
Begin_Read: true
Reading: 652
1: Object
Date: 2018-10-01
Begin_Reading: true
Reading: 851
}
The wrong key was entered for 2018 into the array and needs to be renamed to "Begin_Read". I have a list using another aggregate of all the objects that have the incorrect key. The objects within the array don't have an _id value, so are hard to select. I was thinking I could iterate through the collection and find the array index of the errored Readings and using the _id of the object to perform the $rename on the key.
I am trying to get the index of the array, but cannot seem to select it correctly. The following aggregate is what I have:
[
{
'$match': {
'_id': ObjectId('xxx')
}
}, {
'$project': {
'index': {
'$indexOfArray': [
'$Meter_Readings', {
'$eq': [
'$Meter_Readings.Begin_Reading', True
]
}
]
}
}
}
]
Its result is always -1 which I think means my expression must be wrong as the expected result would be 1.
I'm using Python for this script (can use javascript as well), if there is a better way to do this (maybe a filter?), I'm open to alternatives, just what I've come up with.
I fixed this myself. I was close with the aggregate but needed to look at a different field for some reason that one did not work:
{
'$project': {
'index': {
'$indexOfArray': [
'$Meter_Readings.Water_Year', 2018
]
}
}
}
What I did learn was the to find an object within an array you can just reference it in the array identifier in the $indexOfArray method. I hope that might help someone else.

Remove all items from an array NOT in array in MongoDB

I have two collections in Mongo. For simplification I´m providing a minified example
Template Collection:
{
templateId:0,
values:[
{data:"a"},
{data:"b"},
{data:"c"}
{data:"e"}
]
}
Data Collection:
{
dataId:0,
templateId:0,
values:[
{data:"a",
value: 10},
{data:"b",
value: 120},
{data:"c",
value: 3220},
{data:"d",
value: 0}
]
}
I want to make a sync from Template Collection -> Data Collection, between the template 0 and all documents using that template. In the case of the example, that would mean:
Copy {data:"e"} into the arrays of all documents with the templateId: 0
Remove {data:"d"} from the arrays of all documents with the templateId: 0
BUT do not touch the rest of the items. I can´t simply replace the array, because those values have to be kept
I´ve found a solution for 1.
db.getCollection('data').update({templateId:0},
{$addToSet: {values: {
$each:[
{data:"a"},
{data:"b"},
{data:"c"}
{data:"e"}
]
}}}, {
multi: true}
)
And a partial solution for 2.
I got it. First tried with $pullAll, but the normal $pull seems to work together with the $nin operator
db.getCollection('data').update({templateId:"QNXC4bPAF9J6r9FQu"},
{$pull:{values: { $nin:[
{data:"a"},
{data:"b"},
{data:"c"}
{data:"e"}]
}}}, {
multi: true}
)
This will remove {data:"d"} from all document arrays, but it seems to overwrite the complete array, and this is not what I want, as those value entries need to be persisted
But how can I perform a query like Remove everything from an array EXCEPT/NOT IN [a,b,c,d,...] ?

Jade variable from array // not working

I'm passing an array to the jade document. Then I'd like to access the values of the array via a variable to keep the markup simple. Just see the example below. I have already picked up, that the jade syntax can be quite strange dealing with arrays (stuff like "arr.[0]"). Can you guys tell me what im overseeing here? Big thanks!
- var arr = [
{
name: 'foo',
id: 1
},
{
name: 'bar',
id: 2
}
]
- var item = arr[0];
h2 #{item.id} // doesn't work
h2 #{arr[0].id} // works
h2 #{arr[0].id}
Works because you are referencing the id for arr item in the '0' (first) position. This is because the array starts counting things with a zero, not a one.
As you can probably see from your results, this code would return '1', which means that you could expect h2 #{arr[0].name} To return 'foo'.
To get the ids from both items in the array 'arr', change your code to this.
h2 #{arr[0].id}
h2 #{arr[1].id}

Resources