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 logged
I did const supervisors = q.supervisors ? JSON.parse(q.supervisors) : [];
const supervisors = q.supervisors ? JSON.parse(q.supervisors) : [];
and I got SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse
when console logged.
I did const supervisors = req.body.supervisors.map(sup => sup.userId);
and I got req.body.supervisors.map is not a function
when console logged.
How can I get the supervisors value as [2, 4, 5]?
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.
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); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.