从对象内访问对象?

时间:2016-06-17 05:27:00

标签: javascript

这可能是一个非常新的问题,但我正在学习javascript并使用pouchDB。我有一个返回类似的搜索功能:

{"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]}

我可以很容易地访问total_rows值,但是如何访问'text'的值?

4 个答案:

答案 0 :(得分:1)

只需modelURL

编辑:为了帮助您更好地了解这里发生的事情,您正在使用x.rows[0].doc.text运算符访问“子孩子”。我们要求.内的rows数组然后指定我们想要第一行(记住数组是0索引的,这意味着数组中的第一个元素位于0位置)。

从那里,我们只访问x子项及其包含的doc属性。

答案 1 :(得分:0)

var obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]};

console.log(obj.rows[0].doc.text);

答案 2 :(得分:0)

嗨,请你知道这个

var abc = {
    "total_rows": 1,
    "rows": [
        {
            "id": "mydoc",
            "score": 0.7071067811865475,
            "doc": {
                "title": "Guess who?",
                "text": "It's-a me, Mario!",
                "_id": "mydoc",
                "_rev": "1-21bd9b0c99791947618e98a23134b312"
            },
            "highlighting": {
                "text": "It's-a me, Mario!"
            }
        }
    ]
}

console.log(abc.rows[0].doc.text);
console.log(abc.rows[0].highlighting.text);

答案 3 :(得分:0)

最好通过使用'id'来解析每一行来解析javascript对象。

试试这个(javascript es6)

const obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]}

const id = 'mydoc'
const text = obj.rows.find(item => item.id === id).doc.text
console.log(text)

javascript es5或以前的版本

var obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]};

var id = 'mydoc';
var text = obj.rows.find(function(item) { return item.id === id; }).doc.text;
console.log(text);