我一直试图在我的JSON对象中返回第一个数组的第一个对象,但是我遇到了一些麻烦。
我想在标签中返回第一个"维生素"的名称,这是"维生素B2&#34 ;.
这是我的JSON对象
{
"nutrients": {
"vitamins": [{
"name": "Vitamin B2",
"current": "1.7"
},
{
"name": "Vitamin B6",
"current": "10.9"
}],
"minerals": [{
"name": "Zinc",
"current": "1.7"
}]
}
}
这是我的代码试图映射它
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>
)
}
)}
答案 0 :(得分:1)
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)
答案 1 :(得分:0)
假设整个对象处于state.data
`render(){
const {vitamins}=this.state.data.nutrients;
vitamins.map((item,index)=>{
if(index === 0)
{ return (<div>item.name</div>)
}`
})
}`
输出将打印维生素B2
答案 2 :(得分:0)
你可以使用类似下面的逻辑:
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 : "")
&#13;
答案 3 :(得分:0)
您可以在ES6中使用解构,将其用作参考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>
}