Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Looping over object properties #33

Open
oliverjam opened this issue Mar 29, 2019 · 1 comment
Open

Looping over object properties #33

oliverjam opened this issue Mar 29, 2019 · 1 comment
Assignees

Comments

@oliverjam
Copy link

for (let i = 0; i < 24698; i++) {

I think you've hardcoded 24698 here because that's how many properties are in the JSON?

If you need to loop over an object there are a few options:

  1. Keep using a for loop but use json.length instead of hard-coding the number.
  2. Use a for..of loop which will loop over an object directly.
  3. Get an array of all the keys, values or both using either Object.keys(json), Object.values(json) or Object.entries(json)

e.g.

const getCommonNames = json => {
  const array = Object.values(json).map(value => value.common_name);
  return array;
};
@oliverjam
Copy link
Author

Oh sorry just realised that your json is an array not an object. Most of the above still applies, but you don't need the Object.keys etc. You can just map over the array directly with json.map(item => item.common_name)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants