简体   繁体   中英

How would I assign a variable to destructured data from an API call?

If I have,

let results = null;

try {
    const {
        hits: { hits: queryAsAWhole }
    } = await client.search({
        q:
            "a AND b AND c AND d AND e AND f AND G AND H"
    });

How would I assign queryAsAWhole to results in one call without doing,

let results = null;

try {
    const {
        hits: { hits: queryAsAWhole }
    } = await client.search({
        q:
            "a AND b AND c AND d AND e AND f AND G AND H"
    });

    results = queryAsAWhole;

As a one liner?

you're already using querAsAWhile as an alias for hits , you can either use results as an alias:

const {
  hits: { hits: results }
} = await client.search({

or results would have the return value from an IIFE:

 let results = (() => { try { const obj = { hits: { hits: "hello" } }; const { hits: { hits: queryAsAWhole } } = obj; return queryAsAWhole; } catch (e) { return e; } })(); console.log(results);

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