Creating a data structure that will hold objects in React - reactjs

I'm building a program in React that is basically a questionnaire / survey, so far I've got users answering a bunch of questions then what I am trying to do is take the answers, filter them a bit then return an object to store using Redux. Each question is an object it self that holds different factors than I am trying to measure. Although, I'm getting stuck with actually trying to create the structure of the final object.
I want the object to look something like this:
Results {
Question1 {
factor1: 1,
factor2: 2,
factor3: 3
},
Question2 {
factor1: 3,
factor2: 6
},
and so on...
}
But when I try create create it by saying for example
let results = {
Question1 {
factor1: 0
}
}
React doesn't like it. As soon as I try nest another object inside it returns an error.. Am I missing something simple or do I need to try another approach, any help would be appreciated

It should be like this, property and value needs to be separated by a :
let results = {
Question1 :{
factor1: 0
}
}
let Results= {
Question1: {
factor1: 1,
factor2: 2,
factor3: 3
},
Question2: {
factor1: 3,
factor2: 6
},
and so on...
}

Related

Write data in to nested object in firebase firestore

I have a data structure that looks as follows:
This is the top level of the collection:
I want to write to increment the field count but I can't do it. I've tried so many different methods that I'd rather not go through all of them. The closest I've gotten was through:
const pageRef = admin.firestore().collection("pages").doc(image.page);
pageRef.set(
{
[`images.${image.position}.count`]: admin.firestore.FieldValue.increment(
1
),
},
{ merge: true }
);
But that leaves me with:
Please help. Changing the structure of pages is an option.
This is what I've tried to replicate:
Update fields in nested objects in firestore documents?
The issue is on how the point notaition is being used.
In the Post you shared the example they use is:
var setAda = dbFirestore.collection('users').doc('alovelace').update({
"first.test": "12345"
});
Applying this to your Code and model would be:
const pageRef = admin.firestore().collection("pages").doc(image.page);
pageRef.set(
{
`images[${image.position}].count`: admin.firestore.FieldValue.increment(
1
),
},
{ merge: true }
);
This will affect the element in the Array Images, the element image.position its value count.

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.

Get first object from array of objects in react [duplicate]

This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 4 years ago.
I am trying to get the first object from an array of objects. Fetched data in componentDidMount and return:
var array1 = [
{
Id: 1,
Categories: 200
},
{
Id: 2,
Categories: 100
}
]
(real data is much more complicated but in the same format)
What I want is this:
array2 = [
Id: 1,
Categories: 200
]
I was using
var iterator1 = array1.entries();
let array2 = iterator1.next().value
and when I console.log(array2) it shows the array data (all key and value is in index 1 of array), then when I console.log(array2[1].Id)
it shows undefined right inside the render method in class component. I use the same code in other IDE but not using react the code work. Could someone explain to me please? Appreciate for any help.
Edit:
At the end I found that I asked the wrong question. I failed to get the data because I declared the data in my reducer to object instead of array. I mark the answer by larz since you just need to put index 0 to get the first object from the array of objects.
Grab the first item in your array using [0], which returns an object in your case. Then you can call .Id on it to get the id.
var array1 = [
{
Id: 1,
Categories: 200
},
{
Id: 2,
Categories: 100
}
];
var first = array1[0];
console.log(first, first.Id);

Getting the sum of all values in object - ng-repeat

I feel like I am missing something basic here, and would love some help.
I have some data that looks like this
"playerPoints"{
"ted":{"military":3,"gold":2},
"bill":{"military":2,"gold":4}
}
And an ng-repeat that is player in playerPoints and it shows a list of each players points. But I want a total at the end of each list. That adds up all of that specific players points. In this instance ted would have 5 and bill would have 6.
I have looked around and haven't really come across something that seems like it would work, but this is where the missing basic info could come into play.
Any assistance would be grand.
You need a function in your controller or service that does this in advance. Something like this untested example:
myService.data = {
"playerPoints": {
"ted": {
"military": 3,
"gold": 2
},
"bill": {
"military": 2,
"gold": 4
}
}
};
function sum(obj) {
var sum = 0;
for (var el in obj) {
if (obj.hasOwnProperty(el)) {
sum += parseFloat(obj[el]);
}
}
obj[el]["total"] = sum;
}
sum(myService.data.playerPoints);
In your controller you'll assign a variable to the service property:
ctrl.playerData = myService.data;
Then in your view you can simply output that key's value:
<div ng-repeat="player in ctrl.playerData">
<span>{{player.total}}</span>
...
</div>
If done properly in a service and stored as a property of the service the view will be automatically data-bound and will update dynamically if the object's data changes.

MongoDB update multiple records of array [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
I recently started using MongoDB and I have a question regarding updating arrays in a document.
I got structure like this:
{
"_id" : ObjectId(),
"post" : "",
"comments" : [
{
"user" : "test",
"avatar" : "/static/avatars/asd.jpg",
"text" : "....."
}
{
"user" : "test",
"avatar" : "/static/avatars/asd.jpg",
"text" : "....."
}
{
"user" : "test",
"avatar" : "/static/avatars/asd.jpg",
"text" : "....."
}
...
]
}
I'm trying to execute the following query:
update({"comments.user":"test"},{$set:{"comments.$.avatar": "new_avatar.jpg"}},false,true)
The problem is that it update all documents, but it update only the first array element in every document. Is there any way to update all array elements or I should try to do it manually?
Thanks.
You cannot modify multiple array elements in a single update operation. Thus, you'll have to repeat the update in order to migrate documents which need multiple array elements to be modified. You can do this by iterating through each document in the collection, repeatedly applying an update with $elemMatch until the document has all of its relevant comments replaced, e.g.:
db.collection.find().forEach( function(doc) {
do {
db.collection.update({_id: doc._id,
comments:{$elemMatch:{user:"test",
avatar:{$ne:"new_avatar.jpg"}}}},
{$set:{"comments.$.avatar":"new_avatar.jpg"}});
} while (db.getPrevError().n != 0);
})
Note that if efficiency of this operation is a requirement for your application, you should normalize your schema such that the location of the user's avatar is stored in a single document, rather than in every comment.
One solution could be creating a function to be used with a forEach and evaling it (so it runs quickly). Assuming your collection is "article", you could run the following:
var runUpdate = function(){
db.article.find({"comments.user":"test").forEach( function(article) {
for(var i in article.comments){
article.comments[i].avatar = 'new_avatar.jpg';
}
db.article.save(article);
});
};
db.eval(runUpdate);
If you know the indexes you want to update you can do this with no problems like this:
var update = { $set: {} };
for (var i = 0; i < indexesToUpdate.length; ++i) {
update.$set[`comments.${indexesToUpdate[i]}. avatar`] = "new_avatar.jpg";
}
Comments.update({ "comments.user":"test" }, update, function(error) {
// ...
});
be aware that must of the IDE's will not accept the syntax but you can ignore it.
It seems like you can do this:
db.yourCollection.update({"comments.user":"test"},{$set:{"comments.0.avatar": "new_avatar.jpg", "comments.1.avatar": "new_avatar.jpg", etc...})
So if you have a small known number of array elements, this might be a little easier to do. If you want something like "comments.*.avatar" - not sure how to do that. It is probably not that good that you have so much data duplication tho..

Resources