React中如何将嵌套对象数组转为字符串数组?映射时遇undefined错误
解决映射JSON到字符串数组时的undefined错误
Hey there! Let's break down why you're hitting that undefined issue and fix it right up.
问题出在哪?
Your code has two key issues leading to the undefined result:
- Wrong property access: You tried to get
yourArray.options, butyourArrayis the outer array itself—it doesn't have anoptionsproperty. Each elementelinyourArrayis the object that contains theoptionsarray, so you need to useel.optionsinstead. - Missing return in outer map: Your outer
mapfunction doesn't return the result of the innermap, so it defaults to returningundefinedfor each iteration. That's whynewArrayends up as[undefined].
修正后的代码(保留嵌套结构)
If you might add more objects with options to yourArray later and want to keep the nested array structure, here's the fixed version:
var yourArray = [ { "options": [ { 'id':1, 'name':'All' },{ 'id':2, 'name':'Javascript' },{ 'id':2000, 'name':'Ruby' } ] } ]; var newArray = yourArray.map(function(el) { // Return the inner map result, and access el.options instead of yourArray.options return el.options.map(function(eln) { return eln.name; }); }); console.log(newArray); // Output: [["All", "Javascript", "Ruby"]]
如果你想要一维字符串数组
Since your yourArray only has one object inside, you can directly access its options property to get a flat, clean array:
var yourArray = [ { "options": [ { 'id':1, 'name':'All' },{ 'id':2, 'name':'Javascript' },{ 'id':2000, 'name':'Ruby' } ] } ]; var flatArray = yourArray[0].options.map(function(eln) { return eln.name; }); console.log(flatArray); // Output: ["All", "Javascript", "Ruby"]
内容的提问来源于stack exchange,提问作者H.Husain
相关产品推荐
相关产品推荐

