You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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, but yourArray is the outer array itself—it doesn't have an options property. Each element el in yourArray is the object that contains the options array, so you need to use el.options instead.
  • Missing return in outer map: Your outer map function doesn't return the result of the inner map, so it defaults to returning undefined for each iteration. That's why newArray ends 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:21:21