简体   繁体   中英

How to variable deconstructing by using Spotify Web API

I want to deconstruct two variables from the chained object.

const current = track.spotify.current.metrics.new_collection_listeners;
const previous = track.spotify.previous.metrics.new_collection_listeners;

I thought it would be possible to do something like this

const { current: new_collection_listeners } = track.spotify.current.metrics;
const { previous: new_collection_listeners } = track.spotify.previous.metrics;

But I got the error that the variable is already defined.

Then I thought it would be possible to do something like this:

const { current: { metrics: { new_collection_listeners }}} = track.spotify
const { previous: { metrics: { new_collection_listeners }}} = track.spotify

Or

const {
 previous: { metrics: { new_collection_listeners }},
 current: { metrics: { new_collection_listeners }},
} = track.spotify;

But it is saying that the new_collection_listeners is already defined and previous or current not.

How do I handle this situation?

Both of your attempts would declare new_collection_listeners twice . You need to "rename" the property to a unique name. This done using the property: variableName syntax:

const {
 previous: { metrics: { new_collection_listeners: previous }},
 //                                             ^^^^^^^^^^
 current: { metrics: { new_collection_listeners: current }},
 //.                                           ^^^^^^^^^
} = track.spotify; 

I recommend to read the MDN documentation to learn more about the desutructuring syntax.


const { current: new_collection_listeners } = track.spotify.current.metrics;
const { previous: new_collection_listeners } = track.spotify.previous.metrics;

is the same as

const new_collection_listeners = track.spotify.current.metrics.current;
const new_collection_listeners = track.spotify.previous.metrics.previous;

const { current: { metrics: { new_collection_listeners }}} = track.spotify
const { previous: { metrics: { new_collection_listeners }}} = track.spotify

is the same as

const new_collection_listeners = track.spotify.current.metrics.new_collection_listeners;
const new_collection_listeners = track.spotify.previous.metrics.new_collection_listeners;
const { current: new_collection_listeners } = track.spotify.current.metrics;
const { previous: new_collection_listeners } = track.spotify.previous.metrics;

would define the variable new_collection_listeners twice.

it should be

const { new_collection_listeners: current } = track.spotify.current.metrics;
const { new_collection_listeners: previous } = track.spotify.previous.metrics;

since it is defined like property: variableName . what you did was the opposite

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