简体   繁体   中英

how to access js object properties?

I'm lost on how to get object properties in JS. I'm getting values from firebase and I wanted to filter the result by its id:

//id is from query params (selecting 1 item from view)
const snippet = snippets.filter(snips => {
        if(snips.id == id) return snips;
})

If I console.log after these lines, I'm getting this:

在此处输入图像描述

const obj = snippet[0];        

So I tried to get properties by using snippet[0] which returns this:

在此处输入图像描述

But if I try to get properties such as:

console.log(obj['id']);
//console.log(obj.title); - tried this as well

it returns:

在此处输入图像描述

Entering data:

在此处输入图像描述

This isn't how the array::filter function works. It iterates over the array and the callback returns a boolean true/false if the element should be returned in the result array.

const snippet = snippets.filter(snips => snips.id == id)

Issue

Cannot read property "title" of undefined

This is saying that snippet[0] is currently undefined when trying to access any properties

snippet[0].title , a root title property also doesn't exist in your other console log

Solution

Your snippet is ( possibly ) an array of 1 (or 0) element, so in order to access the title nested in data property

snippet[0].data.title

And in the case that the array is empty or has an element without a data property, use optional chaining or guard clauses to check the access

snippet[0]?.data?.title

or

snippet[0] && snippet[0].data && snippet[0].data.title

looking at what you are asking you need to enter first the data.

console.log(obj[0].data.content)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM