JQuery - .map 不是函数

JQuery - .map is not a function

我有以下代码:

var fieldsJson = formBuilder.actions.getData('json', true);

console.log(fieldsJson);

var nameArr = fieldsJson.map(function (item) { return item.name });

但我不断收到错误消息:

fieldsJson.map is not a function

控制台清楚地显示 fieldsJson 是一个对象数组,如下所示:

[
  {
    "type": "text",
    "label": "Text Field",
    "className": "form-control",
    "name": "testfield",
    "subtype": "text",
    "customField": true
  },
  {
    "type": "text",
    "label": "Text Field",
    "className": "form-control",
    "name": "testfield",
    "subtype": "text",
    "customField": true
  }
]

那么为什么它会为 map 函数抛出错误?

如果fieldsJson是String,需要用JSON.parse解析:

var fieldsJson = formBuilder.actions.getData('json', true);

console.log(fieldsJson);

fieldsJson = JSON.parse(fieldsJson)
var nameArr = fieldsJson.map(function (item) { return item.name });

您几乎可以肯定正在查看 JSON 字符串表示形式。这也将捕获任何格式错误的 json:

try {
  JSON.parse(fieldsJson);
} catch (e) {
  console.log(e);
}

JSON.parse()

的更多信息