In my Vuejs below I want to filter the reviewed:true only questions, and get the length of them, but my code below gives an error TypeError: question.reviewed.includes is not a function ,is there a way to do it?
Here is the screenshot about the json file:
JSON File
filterReviewed() {
return this.questions.filter((question) => {
return (
question.reviewed
.includes('true')
);
});
},
includes is a method of Object of Array type. Directly judge attribute reviewed is OK
filterReviewed (){
return this.questions.filter((question) => question.reviewed);
}
To filter the reviews try this:
filterReviewed() {
return this.questions.filter((question) => question.reviewed === true);
},
To get the filterReviewed length try this:
filterReviewed.questions.length
Related
I am trying to upload an array from my application to Firestone. However, it continues to show
"firebaseError: function fieldvalue.arrayUnion()" called with invalid data.
Here is my code:
const finalList = this.state.players.map(player => {
if(player.Present === true){
return player.id
}
})
finalList.map( id =>
dbh.collection("Groups").doc(this.state.group)
.collection('Enrolled').doc('ids').update({
players: firebase.firestore.FieldValue.arrayUnion(id)
})
)
Note that the array "players" does not exist in the database yet.
You can also use the set with merge approach that i have discussed on comments in question
Other than that you can use
const finalList = this.state.players.map(player => {
if(player.Present === true){
return player.id
}
})
dbh.collection("Groups").doc(this.state.group)
.collection('Enrolled').doc('ids').update({
players: firebase.firestore.FieldValue.arrayUnion(...finalList)
})
you can get the detailed info from answer by Matthew Rideout
It seems like your id variable is an array of IDs, while the arrayUnion function expects a repeatable variable.
To convert the type, you can use the ... operation:
finalList.map( id =>
dbh.collection("Groups").doc(this.state.group).collection('Enrolled').doc('ids').update({
players: firebase.firestore.FieldValue.arrayUnion(...id)
})
)
Alternatively, and more universalle, you can can perform the conversion with this:
firebase.firestore.FieldValue.arrayUnion.apply(null, id);
For more on this, see Gil's answer in this post to the firebase-talk mailing list.
I have some list of names that I take from the array using the Fetch method. Now I'm using the method of searchHandler at the click of a button, I enter the input data into the console:
https://codesandbox.io/s/jovial-lovelace-z659k
But I need to enter the input "First name", and click on the button, only a line with that name was displayed. But I don't know how to make the filter myself.
I found the solution on the internet, but unfortunately I can't integrate it into my code.Here it is:
getFilteredData() {
if (!this.state.search){
return this.state.data
}
return this.state.data.filter(item=>{
return item["firstName"].toLowerCase().includes(this.state.search.toLowerCase())
});
}
How to integrate it into my code? And what to write in the render method?
You are in the right direction there. The correct code (with comments explaining the changes) should be:
searchHandler = search => {
// This if checks if search is empty. In that case, it reset the data to print the initial list again
if (search) {
// This 'arr' variable is a copy of what you do in your Table.js
const arr = this.state.data.group && this.state.data.group.first ? this.state.data.group.first : this.state.data;
const filteredArr = arr.filter((item) => {
// Here you compare with 'search' instead of 'state.search', since you didn't updated the state to include the search term
return item["firstName"].toLowerCase().includes(search.toLowerCase())
})
// This will update your state, which also updates the table
this.setState({data: filteredArr})
} else {
// As explained, if search was empty, return everything
this.resetData();
}
};
// This is a copy of what you have in componentDidMount
async resetData() {
const response = await fetch("/data/mass.json");
const data = await response.json();
this.setState({
data
});
}
Note:
includes is not supported by all browsers, as you can see here. If you need a more reliable solution, you could use indexOf, as explained here.
Since your fetched data is an array of objects, and you basically want to filter out the objects which match the serach criteria, heres how you can write your search handler:
searchHandler = search => {
const { data } = this.state;
const filteredData = {
group: {
first: Object.values(data.group.first).filter(item => item.firstName.includes(search)),
}
}
this.setState({ data: filteredData });
};
Basically, what its doing is taking the array of objects out of dataand filter out only those objects which have the name you search for. and sets the filtered array of objects in the same structure as your original data object is and there you go!!
Also you don't have to make any changes to the render method now. Since render method is already working with the state which has data in it. and as soon as you make a search state, data will be updated and available in the render.
I am trying to retrieve one particular value from within a two-levels deep object data structure. First off, though, I am saving into a variable within the function, like this:
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = sessionStorage.getItem('currentUser');
console.log(userInfo);
}
}
From:
console.log(userInfo);
I get this back in the console:
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
What I want to do is specifically pull out the "_id" value here.
I tried:
console.log(userInfo.data._id);
But then my IDE is showing me an error:
'Property '_id' does not exist on type 'string'.
How do I dig out "_id" in this case?
You are accessing it wrong
Try userInfo.data._id
In the log of your object you can see by the {} notation that data is another object, so after accessing data you can access its properties just as you would with any other object.
I also see that you are getting
'Property '_id' does not exist on type 'string'.
This could mean that you never parsed the information. To find out if this is the case this should be right:
Running->
console.log(userInfo);
Returns->
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
Just after this code:
Running->
console.log(typeof userInfo);
Returns->
"string"
With your edits, I can see that this is the case.
Try:
userInfo = JSON.parse(sessionStorage.getItem('currentUser') );
console.log(userInfo.data._id);
The _id property is under the data key:
const response = {
"token":"sometoken.value",
"data": {
"_id":"8cd0362c0",
"phone":"555-4343"
}
};
console.log(response.data._id)
You can also use destructuring:
const { _id } = response.data;
console.log(_id)
or:
const { data: { _id }} = response;
console.log(_id);
So, as #jonsharpe pointed out, the key was to JSON.parse the string first. So this gets me the value I need for "_id":
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = JSON.parse(sessionStorage.getItem('currentUser'));
console.log(userInfo.data._id);
}
}
Actually your string is returned as JSON string. So you have to parse it into object using JSON.parse() if you are using js or with $.parseJSON() if you are using Jquery. So your updated code now looks like this.
var user ='{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"}}';
var k = JSON.parse(user);
alert(k.data._id);
And Fiddle is here.
Thank You
I would like to read groups_id_ss for specific id.
How to do that in this json?
I successfully read response.docs , but then can't reach id and groups_id_ss.
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"object_type_s:USER",
"indent":"true",
"wt":"json"
}
},
"response":{
"numFound":13,
"start":0,
"docs":[
{
"id":"sanja",
"groups_id_ss":[
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
},
{
"id":"sanjaseconduser",
"groups_id_ss":[
"ACM_SUPERVISOR_DEV",
"CHAIRMAN",
"ACM_ADMINISTRATOR_DEV",
"CPC INITIATOR",
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
}
]
}
}
As stated you could read response.docs from json. Let's say
var docs = response.docs;
As docs is an array you can use forEach to loop thruogh each element
docs.forEach(function(doc) {
if(doc.id === "desired_Id") {
var groupIdSS = doc.groups_id_ss;
}
});
This way you can read groups_id_ss for desired id.
Hope it helps.
Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json
You can write code like this in your spec file:
var responseData = require('../../response.json');
describe('some function description', function(){
var groupID = responseData.response.docs[0].groupid_ss[0];
var groupID = responseData.response.docs[0].groupid_ss[0]
});
Since that is json array, we have to give the index of the array in that.
Hope this would work for you.
I have a json file in a folder called json/img_desc.json
Here is the json file
{ "theimages":[
{
"number":1,
"title":"Joy Toy teddy bear",
"description":"In etc etc"
} etc etc
Then I used this code to try and get the first value.
$.getJSON('json/img_desc.json', function(theimages) {
console.log(img_desc.theimages.number[0]);
});
The error
It says this
[15:06:46.951] ReferenceError: img_desc is not defined #
file:///[removed for privacy]/js/puzzle.js:246
it should be
$.getJSON('json/img_desc.json', function (theimages) {
console.log(theimages.theimages[0].number);
//if you want to loop
$.each(theimages.theimages, function (idx, obj) {
console.log(obj.number)
})
});
Documentation says http://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success-data--textStatus--jqXHR- it will pass a plain object as the second parameter. So, you can do something like this
$.getJSON('json/img_desc.json', function(theimages) {
$.each(theimages.theimages, function( index, val ) {
console.log(val, val.number);
});
});
$.getJSON('json/img_desc.json', function(img_desc) {
console.log(img_desc.theimages.number[0]);
});
Should fix your problem. As if you have any other problem, ask it in a separate question.