Reputation: 695
I know that maybe i will sound stupid for some people , but i am trying to extract single value from my array and insert it into a variable . How was possible to do it . In my case i want to have a new variable with the value only of the fileId
const arrayOfFiles = rowData.files;
Output :
[{…}, {…}]
0: {fileId: 166, fileExtension: "CSV"}
1: {fileId: 167, fileExtension: "XLSX"}
lastIndex: (...)
lastItem: (...)
length: 2
__proto__: Array(0)
Tryout
arrayOfFiles.forEach(file=> console.log(file.fileId));
Output
166
167
But how can i insert this value into a single variable ? I gave a try something like this :
const fileId = arrayOfFiles.forEach((file) => file.fileId);
But it returns me undefined
. Any suggestions what am i doing wrong ?
Upvotes: 0
Views: 176
Reputation: 980
the problem is with the forEach, unlike map, filter, reduce, find, etc.. it doesn't return any value, hence you're getting undefined.
const res = arrayOfFiles.forEach(file => file.fileId); // undefined
const res = arrayOfFiles.map(file => file.fileId); // [166, 167]
const res = arrayOfFiles.filter(file => file.fileId === 166); // [166]
const res = arrayOfFiles.find(file => file.fileId === 166); // 166
Upvotes: 0
Reputation: 91
const arrayOfFiles = [{fileId: 166, fileExtension: "CSV"}, {fileId: 167, fileExtension: "XLSX"}];
var ids = arrayOfFiles.map((file) => file.fileId);
console.log(ids)
Upvotes: 1