I am trying to create record from a form data. When I console.log(req.body) I get the following record.
req.body => [Object: null prototype] {
id: '1',
key1: 'Value1',
key2: 'Value2',
supervisors: '[object Object],[object Object],[object Object]'
}
So I checked the database where the record is stored and see that supervisors is stored as:
supervisors: Array(3)
0:
name: "Reporter"
userId: 4
1:
name: "Officer 1"
userId: 5
2:
name: "Coordinator"
userId: 2
I will like to get the values of userId as an array in supervisors field in the req.body so that my req.body will look like:
req.body => [Object: null prototype] {
id: '1',
key1: 'Value1',
key2: 'Value2',
supervisors: '[4, 5, 2]'
}
I did
const supervisors = JSON.stringify(req.body.supervisors))and I got[object Object],[object Object],[object Object]when console loggedI did
const supervisors = q.supervisors ? JSON.parse(q.supervisors) : [];and I gotSyntaxError: Unexpected token o in JSON at position 1 at JSON.parsewhen console logged.I did
const supervisors = req.body.supervisors.map(sup => sup.userId);and I gotreq.body.supervisors.map is not a functionwhen console logged.
How can I get the supervisors value as [2, 4, 5]?
2 Answers 2
Use map()
const supervisors = q.supervisors.map(sup => sup.userId);
You don't need to use any JSON functions, as the data you show has already been parsed into an array of objects.
6 Comments
UnhandledPromiseRejectionWarning: TypeError: q.supervisors.map is not a functionq was the object you showed in the question. If not, replace it with the correct variable.req.body.supervisors.map is not a function[object Object].As mentioned above, map() is the correct one-line approach.
map() using an arrow function (which has an implicit return) is also the ideal approach if you need to chain further transformations.
The alternative (verbose but also lightning-fast) approach is (that old work-horse) the for loop.
Working Example:
// THE OBJECT
const myObject = {
supervisors: [
{
name: 'Reporter',
userId: 4
},
{
name: 'Officer 1',
userId: 5
},
{
name: 'Coordinator',
userId: 2
}
]
};
// THE SUPERVISORS ARRAY (NOT YET POPULATED)
const supervisors = [];
// LOOP THROUGH THE ARRAY IN THE OBJECT TO POPULATE THE SUPERVISORS ARRAY
for (let i = 0; i < myObject.supervisors.length; i++) {
supervisors.push(myObject.supervisors[i].userId);
console.log(supervisors);
}
5 Comments
UnhandledPromiseRejectionWarning: ReferenceError: myObject is not definedmyObject is an example name (like foo and bar) - in the example above, it's a stand-in for whatever variable name you're actually using.map() function; 2) using a for loop . You surely have enough to write your own working code at this point. Are there any parts of either of those two answers which are not making sense to you?Explore related questions
See similar questions with these tags.
const superIds = supervisors.map(s => s.userId);