1

have file_name.JSON, like

[{"id": 1},{"id": 2},{"id": 3}]

How can I use "for" to get in final: 1,2,3

const file_name = [{
  "id": 1
}, {
  "id": 2
}, {
  "id": 3
}]

for (let i = 0; i <= file_name.length; i++) {
  console.log(file_name[i].id);
}

Or maybe another way, not use "for"

4
  • 1
    Your code works, aside for the off-by-one typo Commented Mar 1, 2019 at 21:13
  • 1
    Yes, Max, can you be a bit clearer on the result you are expecting. Commented Mar 1, 2019 at 21:16
  • You want map or reduce Commented Mar 1, 2019 at 21:20
  • You don't want to let your loop equal length. that'll give an id of undefined error. Are you asking about the usage of the loop or how to fetch the file? Commented Mar 1, 2019 at 21:26

3 Answers 3

1

To fix your code you need just to change i <= file_name.length to i < file_name.length

const file_name = [{
  "id": 1
}, {
  "id": 2
}, {
  "id": 3
}]

for (let i = 0; i < file_name.length; i++) {
  console.log(file_name[i].id);
}

Or for a better and clean code you can use map

const file_name = [{
  "id": 1
}, {
  "id": 2
}, {
  "id": 3
}]

const res = file_name.map(({
  id
}) => console.log(id));

Sign up to request clarification or add additional context in comments.

Comments

0

Use map

const file_name = [{
  "id": 1
}, {
  "id": 2
}, {
  "id": 3
}]

let arr = file_name.map(e => e.id);
console.log(arr);

let str = file_name.map(e => e.id).join();
console.log(str);

1 Comment

At the end he states "Or maybe another way, not use "for""
0

No, you don't have JSON, you have a plain old Javascript array there.

var file_name = [{"id": 1},{"id": 2},{"id": 3}];
var justNumbers = file_name.map(e => e.id);
console.log(justNumbers);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.