John White
John White

Reputation: 131

Iterating over multiple arrays in JSON object in React

I've been trying to return the first object of the first array in my JSON object, but I'm having some trouble.

I want to return the name of the first "vitamins", which is "Vitamin B2", in an tag.

Here is my JSON object

{
  "nutrients": {
    "vitamins": [{
      "name": "Vitamin B2",
      "current": "1.7"
    },
    {
      "name": "Vitamin B6",
        "current": "10.9"
    }],
      "minerals": [{
        "name": "Zinc",
        "current": "1.7"
    }]
  }
}

And here is my code trying to map over it

import nutrients from '../../vitamins.json';

renderData() {
  return Object.keys(nutrients).map((nutrient, index) => {
    console.log('it works', nutrient[0].name, index);
    return (
      <option value="" key={index}>{nutrient[0].name}</option>
    )
  }
)}

Upvotes: 2

Views: 2266

Answers (4)

Jeeva
Jeeva

Reputation: 1590

You may use destructuring in ES6, use this as reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring

import nutrients from '../../vitamins.json'
renderData() {
  const { nutrients: { vitamins: [{ name: vitaminName }] }  } = nutrients; //it destructures the given object, it will directly fetch the vitamin B2.
  console.log("Vitamin Name is = "+vitaminName)
  <option value="">{vitaminName}</option>
}

Upvotes: 0

Raeesaa
Raeesaa

Reputation: 3316

You could use logic something like below:

let nutrientObj = {
  "nutrients": {
    "vitamins": [{
      "name": "Vitamin B2",
      "current": "1.7"
    },
    {
      "name": "Vitamin B6",
        "current": "10.9"
    }],
      "minerals": [{
        "name": "Zinc",
        "current": "1.7"
    }]
  }
}

let nutrients = nutrientObj.nutrients;
let firstElement = nutrients[Object.keys(nutrients)[0]];

console.log(firstElement && firstElement.length ? firstElement[0].name : "")

Upvotes: 0

Erick
Erick

Reputation: 1146

Assuming the entire object to be in state.data

`render(){
 const {vitamins}=this.state.data.nutrients;
 vitamins.map((item,index)=>{
     if(index === 0)
     {    return (<div>item.name</div>)
     }`
  })
 }`

the output will print Vitamin-B2

Upvotes: 0

Akhil Aravind
Akhil Aravind

Reputation: 6130

var a ={
  "nutrients": {
    "vitamins": [{
      "name": "Vitamin B2",
      "current": "1.7"
    },
    {
      "name": "Vitamin B6",
        "current": "10.9"
    }],
      "minerals": [{
        "name": "Zinc",
        "current": "1.7"
    }]
  }
}

console.log(a.nutrients['vitamins'][0].name)

Upvotes: 1

Related Questions