简体   繁体   中英

Destructuring Nested Object

I'm trying to play around ES6 and trying to convert a ES5 function to ES6.

ES5:

const ResponseData = {
    items: [{name: 'Matt'}]
}

function getName(ResponseData) {
    let itemDetails = ResponseData && ResponseData.items && ResponseData.items[0];
    return itemDetails.name;
}

However, I am not sure how to access items[0] in ES6 destructuring.

Here's my attempt:

function getItemES6(ResponseData) {
 const { items : item = []   } = ResponseData;
 return item;
}

This is pretty much giving me item array, how do I get items[0] and check for .name using ES6?

Little confused with destructuring. Can someone enlighten?

You can destructure nested objects and arrays, add add empty object/array as default to get undefined if value doesn't exist:

 const ResponseData = { items: [{name: 'Matt'}] }; const getItemES6 = ({ items: [{ name } = {}] = [] }) => name; console.log(getItemES6(ResponseData)); 

You destructure objects as such:

const { key: yourVar = 'defaultVal' } = obj

Arrays are similar, but instead of referencing keys, you reference the elements themselves: const [ firstElem, secondElem ] = arr

 const obj = { a: 1, b: { b1: 'a' } }; const objWithArr = { a: 1, b: [{ key: 5, }, { key: 6 }] } const { b: { b1: b1Val = 'default', } = {}, } = obj; const { b: [{ key: firstKey, } = {}, { key: secondKey, } = {} ] = [], } = objWithArr; console.log(b1Val); console.log(firstKey); console.log(secondKey); 

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