0

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 ?

2
  • What value do you expect fileId to have? 166 or 167? Or maybe an array with both? Or is that not what you're asking? Commented May 20, 2020 at 10:14
  • Basically const fileId should be equal to file.fileId , because on click i can detect which id is requested Commented May 20, 2020 at 10:17

2 Answers 2

1
const arrayOfFiles = [{fileId: 166, fileExtension: "CSV"}, {fileId: 167, fileExtension: "XLSX"}];
var ids = arrayOfFiles.map((file) => file.fileId);
console.log(ids)
Sign up to request clarification or add additional context in comments.

2 Comments

Not exactly . I am not expecting new arrays of files.fileId
What you are expecting? I thought you want - how can i insert this value into a single variable ?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.