1

I created a simple Component where I organize names, however I have troubles getting the names in my JSON file.

Here is what my JSON file looks like

{
  "tasks" : [
    { 
      "id": 1, 
      "name": "Studies", 
      "status": "Completed", 
      "progress": 100
    },
    { 
      "id": 2, 
      "name": "Writing",
      "status": "In Progress", 
      "progress": 91
    }
  ]
}

And the function in my React Component

function orderA() {
  data.tasks.map((t) => 
    console.log(t.name)
  );
  const noms = data.tasks.name;
  noms.sort();
  console.log(noms);
}

I call the function by clicking on a button, console.log(t.name) show the names I need to use but data.tasks.name gives me an undefined error but if I put names in my const my function is working.

1
  • 1
    I'd like to note that where you're doing data.tasks.map(t => console.log(t.name)), you should rather use data.tasks.forEach(t => console.log(t.name)). The result is the same, but the .map-function is meant for tranforming data in an array, while the .forEach-function is meant for doing an operation (or several) on every item in an array (like you're doing). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 19, 2021 at 16:34

2 Answers 2

4

You need to acces the names inside the loop, because data.tasks is an array :

orderA() {
  const noms = data.tasks.map((t) => t.name).sort();
  console.log(noms);
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's because when you set the noms variable you're accesing to tasks which is an array. And you're referencing the complete tasks array that does not have a name attribute.

You'll need to iterate through the tasks array or to select an specific position of the array, and then access the name attribute of the object in that position of the array.

Example: data.tasks[0].name.

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.