我正在运行将查询发送到Elasticsearch实例的node.js服务器。这是查询返回的JSON的示例:

{
    "took": 2,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 9290,
        "max_score": 0,
        "hits": []
    },
    "suggest": {
        "postSuggest": [
            {
                "text": "a",
                "offset": 0,
                "length": 1,
                "options": [
                    {
                        "text": "Academic Librarian",
                        "score": 2
                    },
                    {
                        "text": "Able Seamen",
                        "score": 1
                    },
                    {
                        "text": "Academic Dean",
                        "score": 1
                    },
                    {
                        "text": "Academic Deans-Registrar",
                        "score": 1
                    },
                    {
                        "text": "Accessory Designer",
                        "score": 1
                    }
                ]
            }
        ]
    }
}

我需要创建一个包含每个职位作为字符串的数组。我遇到了这种奇怪的行为,我无法弄清楚。每当我尝试从JSON中提取值时,都无法进入options之下,否则所有内容都将返回未定义状态。

例如:
arr.push(results.suggest.postSuggest)将实现您所期望的:postSuggest中的所有内容。

即使在没有arr.push(results.suggest.postSuggest.options)的情况下运行.options,它也会显示为undefined。对于.options以下的任何内容也是如此。

我认为这可能是因为.options是作用于变量的某种内置函数,因此与其将选项视为JSON,而是尝试在results.suggest.postSuggest上运行一个函数

最佳答案


postSuggest是一个对象数组。 options内的postSuggest也是对象数组。所以首先您需要通过postSuggest[0]获得postSuggest,然后postSuggest[0].options获取options数组

下面的代码片段可能很有用

 var myObj = {..}
// used jquery just to demonstrate postSuggest  is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest  //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
  document.write("<pre>Score is "+ item.score + " Text</pre>")
})

Jsfiddle

09-15 16:59