简体   繁体   中英

What is the most efficient way to retrieve properties from a nested JavaScript object?

I consume an API that has nested data. The data is sent in small pages (<10 JSON objects at a time) and the information retrieved is only used on that page, it does not persist across the session. I have experimented with Immutable JS and Native JS to store the JSON. My issue with using immutable is that for the information to be rendered into the template it would go through a series of type conversions like this.

    JSON -> JS -> ImmutableMap -> JS

So I have preferred to use native JS. The downside is that immutable JS's API is very convenient for retrieving a field in a map using getIn(). With native JS I use square brackets to access a nested object field.

    const A = { B : { C: D }};
    const d = A['B']['C'];

This can be very verbose. I'm not sure if immutable JS offers better performance for my use-case. It is not a large map of objects and I assume there is some overhead in converting from JS to immutable back to JS. But, I'm also not sure how defensive it is to access nested object properties using square brackets.

Access with dot

You can access your data as follow:

const A = { B : { C: 'D' }};
const d = A.B.C;

There doesn't seem to be much difference between accessing a property with brackets or with dot operator.

Destructuring

You can also achieve the exact same thing with destructuring:

const A = { B : { C: 'D' }};
const { B: { C: d }} = A;

handle undefined

To avoid undefined, you can use default values in destructuring:

const getD = ({B : { C :d } = {}} = {}) => console.log(d)
getD(undefined);// -> undefined

Or

const { B: { C : d } = {} } = {}
console.log(d); // -> undefined

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