When I did a console.log(dbdata.user) it returned:
createdAt: "2020-11-17T04:32:17.934Z"
date: "2020-11-17T04:32:17.931Z"
displayname: "Batman"
followers: ["5fbb3879e8902d14f8c60448"]
updatedAt: "2020-12-02T14:58:17.880Z"
__v: 0
_id: "5fb35251888e8d081c06a7fa"
__proto__: Object
But when I did a console.log(dbdata.user.followers), it returned undefined. What am I missing here?
I am using useEffect and the state code:
const [dbdata,setDBData] = useState({post:[],user:[]})
useEffect(async() => {
const response = await Axios.get('http://localhost:5000/api/posts/allpost', {withCredentials:true})
setDBData(response.data)
}, [])
Many thanks in advance and greatly appreciated.
You have declared the user to be of type Array in useState Hook. While you are trying to access dbdata.user.followers which points out that the user is of type object. Try changing the console statement to below.
EDIT:
You need to flatten the followers array before searching for values. Because it's an array inside an array.
var user = [
{
'createdAt': "2020-11-17T04:32:17.934Z",
'date': "2020-11-17T04:32:17.931Z",
'displayname': "Batman",
'followers': ["5fbb3879e8902d14f8c60448"],
'updatedAt': "2020-12-02T14:58:17.880Z"
},
{
'createdAt': "2020-11-17T04:32:17.934Z",
'date': "2020-11-17T04:32:17.931Z",
'displayname': "Batman",
'followers': ["123"],
'updatedAt': "2020-12-02T14:58:17.880Z"
}
]
var followersArray = [];
user.forEach(e => followersArray.push(...e.followers))
console.log(followersArray.includes("123"))
console.log(followersArray.includes("00000"))
Related
So I'm using mongodb to fetch some data from the database.
The issue is when I try to check for something in an array
Here is what the structure looks like:
Example array structure
{ // ...
likedPeople: [
{
name: "foo"
image: "test",
},
{
name: "bar",
image: "baz",
}
]
}
This is the array i get Back.
So when i try to find if it includes a certain value,
eg:
const displayName = "foo";
console.log(
likedPeople.map((likedPerson) => {
return likedPerson.name === displayName; // Output: [true, false]
})
);
But then If i again try to do some other method on it like map() or includes(), It breaks the setup:
const response = likedPerson.name === displayName; // Output: [true, false]
response.map((res) => console.log(res)); // Output: ERROR: response.map() is not a function
But the fact is that I am getting an array with the values, so what am I even doing wrong here?
I tried adding an optional chaining response?.map() but still it gave me the same error.
Also the includes() method also returns me the same response.includes is not a function error.
Can anyone help?
Use the some method to check the name exists in likedPeople :
const likedPeople = [
{
name: "foo",
image: "test",
},
{
name: "bar",
image: "baz",
}
];
const displayName = "foo";
const isExist = likedPeople.some(people => people.name === displayName);
console.log(isExist)
Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};
I want to find a value inside an array that is already inside an array.
To give an example of my array:
[
{
ConcessionId: 1,
ConcessionName: "Coyotes",
KnownAs: [
{
TeamId: 1,
Name: "Arizona Coyotes",
},
{
TeamId: 2,
Name: "Phoenix Coyotes",
}
]
},
{
ConcessionId: 2,
ConcessionName: "Devils",
KnownAs: [
{
TeamId: 3,
Name: "Colorado Rockies",
},
{
TeamId: 4,
Name: "New-Jersey Devils",
}
]
}
]
What I want is when Icall my function it returns me the team name.
For example, I the parameter value is 3, I want Colorado Rockies as a name:
public getInfo(_TeamID) {
const concession: ConcessionInfo[] = this.concessionList$.filter(function (x) {
x.KnownAs.filter( (y)=> {
y.TeamId= +_TeamID;
return y.Name;
})
})
}
I try so many different way with filter. But never get something good. Never works.
I can make a double .foreach , for each array. but I think a better method exist than making a double loop.
Thanks
Instead of using the filter method (which is in fact working similar as a for loop), you could do forEach on both arrays. For your current data structure, there is no other way around it.
getInfo = (_TeamID) => {
let teamName = '';
this.concessionList$.forEach(entry => {
entry.KnownAs.forEach(team => {
if(team.TeamId === _TeamID){
teamName = team.Name;
return; // break the loop.
}
})
});
return teamName;
}
Here is a working example
https://stackblitz.com/edit/double-for-lopp
EDIT
If you have a look at the polyfill implementation of filter from Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter which is in equivalent to the native implementation of filter, you can see that it is looping through the whole array, the same way as a forEach loop. The difference is that the filter method will return a new array based on the boolean condition inside the callback function, while a forEach loop does not return anything.
Assuming myArray is contains the data you provided.
The following code will work if you're using Typescript 3.7 and above.
public getInfo(teamId: number): string | undefined {
const team = this.concessionList$
.map(concession => concession.KnownAs)
.reduce((a, b) => a.concat(b), [])
.find(team => team.TeamId === teamId)
return team ? team.Name : undefined
}
Usage:
this.getInfo(3) // Colorado Rockies
Ok how this work?
You have to understand what is find. For example:
const result = [{name: 'foo', age: 1}, {name: 'bar', age: 2}]
.find(people => people.name === 'foo')
console.log(result) // {name: 'foo', age: 1}
I have this componentDidMount function:
componentDidMount() {
const { insurances } = this.props;
const insuranceId = this.props.match.params.id;
const insurance = insurances.find(insurance => insurance.id == insuranceId);
this.setState({ insurance: insurance }, () => {
console.log("insurance", this.state.insurance.tip); <--- this is what i am talking about
});
}
That console.log() returns an object. But if i change it to console.log(this.state.insurance.tip) which is one of the properties, I get the error: TypeError: Cannot read property 'tip' of undefined. I don't really understand how mounting works. Could it be because it is not mounted? If so, how do i fix it?
EDIT
console.log('insurance', insurance), before setState is corect:
id: 1, user_id: 1, tip: "Asigurare", date_exp: "1974-10-14", date_notif: "1975-10-03", …}
created_at: "2019-03-15 10:54:40"
date_exp: "1974-10-14"
date_notif: "1975-10-03"
id: 1
note: "Nam id ipsam sequi."
tip: "Asigurare"
updated_at: "2019-03-15 10:54:40"
user_id: 1
but if I do console.log(this.state.insurance) returns an object with undefined properties
EDIT 2
I think this is close to what i have https://codesandbox.io/s/n72rx0k660
The way you have defined your state is the issue.
You have it as
state = {
insurance: [
{
tip: "1"
}
]
};
Change it to :
state = {
insurance:
{
tip: "1"
}
};
For you to access it as this.state.insurance.tip it needs to be a key in the insurance object. What you have right now it this.state.insurance[0].tip
Since insurance is an array right now.
lmk if this needs more clarification.
I am using a combination of filter, some, and includes to return a filtered set of documents in my MongoDB/Node back-end environment.
While I can get this to work in a mock example, when I plug it in to my actual data, I get an error.
This is the key problematic piece of code:
let filteredDocs = docs.filter(doc => doc.branches._id.some(branch => mongoArrBranchID.includes(branch._id)));
When I console.log this out with:
console.log("filteredDocs: ", filteredDocs);
I get:
Reason: TypeError: Cannot read property 'some' of undefined
I've been scratching my head trying to figure out what the issue is here. Why is my mock example working, but not this?
One thought I had was that maybe the issue is that the comparison is made with different types. So then I checked with these two lines of code to make sure the comparison is using Mongo ObjectIDs in both cases (both return true):
console.log("is param value valid: ", mongoose.Types.ObjectId.isValid(mongoArrBranchID[0])); // returns true
console.log("is doc value valid: ", mongoose.Types.ObjectId.isValid(docs[0].branches[0]._id)); // returns true
So why am I getting the TypeError: Cannot read property 'some' of undefined error here?
By the way, just so you know what the data looks like, my passed-in filter values when consoled out look like this :
console.log("mongoArrBranchID: ", mongoArrBranchID); // result below
mongoArrBranchID: [ 5ac26645121f0613be08185d, 5ac26645121f0613be08185a ]
And again, this check returns true:
console.log("is param value valid: ", mongoose.Types.ObjectId.isValid(mongoArrBranchID[0])); // returns true
My docs data looks like this when I console out the first of the docs:
console.log("doc branches: ", docs[0].branches); // result below
doc branches: [{"_id":"5ac26645121f0613be08185a","name":"New York"},{"_id":"5ac26645121f0613be08185d","name":"Los Angeles"},{"_id":"5ac26648121f0613be081862","name":"Charlotte"},{"_id":"5ac2664a121f0613be081869","name":"Chicago"},{"_id":"5ac2664a121f0613be08186e","name":"Seattle"}]
When I console out just the first branches._id value, like so:
console.log("doc branch: ", docs[0].branches[0]._id);
I get:
doc branch: 5ac26645121f0613be08185a
And again, this check on the whether the value is a valid Mongo Object ID returns true:
console.log("is doc value valid: ", mongoose.Types.ObjectId.isValid(docs[0].branches[0]._id)); // returns true
So what's the problem here? Why am I getting this error:
Reason: TypeError: Cannot read property 'some' of undefined
When I do:
let filteredDocs = docs.filter(doc => doc.branches._id.some(branch => mongoArrBranchID.includes(branch._id)));
console.log("filteredDocs: ", filteredDocs);
And for extra clarification, when I use mock data in ScratchJS in Chrome, this works for me:
let docs = [
{
_id: "5ba39a12179b771820413ad8",
name: "Samson",
branches: [{ _id: "3nc26645121f0613be08167r", name: "New York" }, { _id: "3fc26645121f0613be08185d", name: "Los Angeles" }, { _id: "2hc26648121f0613be081862", name: "Seattle" }, { _id: "7jc2664a121f0613be081869", name: "Chicago" }, { _id: "7ju2664a121f0613be08186e", name: "Charlotte" }],
updatedAt: "2018-09-20T13:01:06.709Z",
createdAt: "2018-09-20T13:01:06.709Z"
},
{ _id: "3ya39a12179b771820413af5", name: "Sarah", branches: [{ _id: "3nc26645121f0613be08167r", name: "New York" }, { _id: "5ac26645121f0613be08145d", name: "Miami" }, { _id: "5ac2664a121f0613be08154s", name: "Sacramento" }], updatedAt: "2018-09-20T13:01:06.709Z", createdAt: "2018-09-20T13:01:06.709Z" },
{ _id: "2sa39a12179b771820413gy4", name: "Tim", branches: [{ _id: "1rd26645121d5613be08167h", name: "Denver" }, { _id: "5ac2664a121f0613be08154s", name: "Sacramento" }], updatedAt: "2018-09-20T13:01:06.709Z", createdAt: "2018-09-20T13:01:06.709Z" }
];
let filterValues = ["5ac26645121f0613be08145d", "7ju2664a121f0613be08186e"];
let filteredDocs = docs.filter(doc => doc.branches.some(branch => filterValues.includes(branch._id)));
console.log(filteredDocs);
So what's the difference? Why does it work in the mock example but not with my actual data?
It is because docs.branches is an array, and therefore does not have the _id attribute you have accessed on it. You should revise your code to the following:
let filteredDocs = docs.filter(doc => doc.branches.some(branch => mongoArrBranchID.includes(branch._id)));
The error you received occurred because accessing an non-existent attribute of an object returns undefined, so doc.branches._id returned undefined, and trying to access an attribute of undefined, some in this case, throws an error.
EDIT:
I want to clarify that the mistake is you wrote doc.branches._id.some instead of doc.branches.some in your code. The issue is the _id part.