i have an array of objects that looks like this:
invitations: Array<record> = [new record()];
interface recordMap {
value:string;
err:string
}
export class record{
number: recordMap ;
deptNumber: recordMap ;
boothNumber: recordMap ;
primaryEmail: recordMap ;
members: recordMap [];
}
my backend request body has to look like this
[
{
"number": "string",
"deptNumber": 0,
"boothNumber": "string",
"primaryEmail": "string",
"members": [
"string"
]
}
]
this is what i have tried so far
my struggle is for the members property because it is an array in the invitation array and I am trying to get only the value from it and push it to the request body array members.
the result of my code is code 400 bad request.
How can i make this object?
const invitationArray = [];
this.invitations.forEach(invitation => {
invitationArray.push({
number: invitation.number.value,
deptNumber: invitation.deptNumber.value,
boothNumber: invitation.boothNumber.value,
primaryEmail: invitation.primaryEmail.value,
members: invitation.members.forEach(number => number.value)
});
});
You could try to use array map method. From the docs:
The map() method creates a new array populated with the results of
calling a provided function on every element in the calling array.
var members = [{ value: 'value1', error: 'error1' }, { value: 'value2', error: 'error2' }, { value: 'value3', error: 'error3' }, { value: 'value4', error: 'error4' }]
console.log(members.map(member => member.value));
Try the following
const invitationArray = [];
this.invitations.forEach(invitation => {
invitationArray.push({
number: invitation.number.value,
deptNumber: Number(invitation.deptNumber.value),
boothNumber: invitation.boothNumber.value,
primaryEmail: invitation.primaryEmail.value,
members: invitation.members.map(member => member.value)
});
});
Also it appears deptNumber property is expected to be of type number. I've converted it to number as well.
Related
I get a CastError when trying to save items to MongoDB using $each . I use FormData to send the array. If I display the array in the backend, everything is correct. I just can't store it in MongoDB
Frontend:
let array = ["ONE","TWO","THREE"]
let data = new FormData();
data.append("tags", JSON.stringify(array));
Backend:
const update = await newArt.updateOne(
{
$push: {
tags: {
$each: [JSON.parse(req.body.tags)],
},
},
},
{ new: true }
);
CastError: Cast to string failed for value "[
'ONE',
'TWO',
'THREE'
]" (type Array) at path "tags"
Schema:
tags: {
type: [String],
require: true
},
You are using 2 arrays; one inside the req.body.tags and one around the JSON.parse, Try removing the external one:
const update = await newArt.updateOne(
{
$push: {
tags: {
$each: JSON.parse(req.body.tags),
},
},
},
{ new: true }
);
See how it works on the playground example
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 am trying to create an array containing only id's from the state.words object (below)
MY REQUIRED OUTPUT
['word-1','word-2','word-3','word-4','word-5','word-6','word-7']
My starting data structure looks like this
words: {
'word-1': { id: 'word-1', content: 'Jimmy Yukka' ,url:'www.paulayling.me'},
'word-2': { id: 'word-2', content: 'INXS' ,url:'www.paulayling.me'},
'word-3': { id: 'word-3', content: 'Up North' ,url:'www.paulayling.me'},
'word-4': { id: 'word-4', content: 'Prince' ,url:'www.paulayling.me'},
'word-5': { id: 'word-5', content: 'Magic Moose' ,url:'www.paulayling.me'},
'word-6': { id: 'word-6', content: 'Salt n Pepper' ,url:'www.paulayling.me'},
'word-7': { id: 'word-7', content: 'Maddonna' ,url:'www.paulayling.me'}
}
The problem I have is that because it is an object array based methods will not give me the result I need eg below does not work - but I need an equivalent for an object of objects
My function is below
addNewWord() {
var currentOrder = this.state.words.map(function (book) {
return book.id
})
console.log('words stuff', currentOrder)
}
I get the error
TypeError: this.state.words.map is not a function
The function is called from the componentDidMount() function if it is relavant
map can only be used on arrays. If you want to list the keys in your words object, you can do it this way:
const result = Object.keys(this.state.words);
This will return your required output
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}