bufferjg
bufferjg

Reputation: 11

Accessing objects from within object?

This is probably a very newbish question, but I am learning javascript and working with pouchDB. I have a search function that returns something like:

{"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!"}}]}

I can access the total_rows value easily obviously, but how would I access the value of 'text'?

Upvotes: 1

Views: 54

Answers (4)

Alongkorn
Alongkorn

Reputation: 4217

it is better to identify each row by using 'id' to parse javascript object.

try this (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 or previous version

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);

Upvotes: 0

Gayathri Mohan
Gayathri Mohan

Reputation: 2962

Hi please cchecck this

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);

Upvotes: 0

Manatax
Manatax

Reputation: 4223

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);

Upvotes: 0

Singular1ty
Singular1ty

Reputation: 2615

Simply with x.rows[0].doc.text.

Edit: To help you understand a little better what's happening here, you're accessing "sub children" with the . operator. We're asking for the rows array inside x and then specifying we want the first row (remember that arrays are 0-indexed, meaning the first element in an array is at position 0).

From there, we just access the doc child, and the text attribute it contains.

Upvotes: 1

Related Questions