[英]How to make a destructuring of this array of objects
I'm trying to use destructuring on elements of my subItems
array to get variables that refer directly to the links
and open
properties.我正在尝试对我的
subItems
数组的元素使用解构来获取直接引用links
和open
属性的变量。
Specifically, I'm trying to use the following code, which fails as specified in the comments.具体来说,我正在尝试使用以下代码,如注释中指定的那样失败。
const [{links, open}] = subItems.map(({ items }) => {
document.getElementById(items);
}); // Fails: returns nothing
const {links, open} = subItems((items ) => {
return items;
}); // Fails: returns only the first `link` and `open`
// This is what the `subItems` array looks like:
export const subItems = [
{
links: [
{ title: 'ret', to: '#' },
{ title: 'def', to: '#' },
{ title: 'rev', to: '#' },
{ title: 'red', to: '#' },
{ title: 'im', to: '#' },
{ title: 'glossar', to: '#' }
],
open: true
},
{
links: [
{ title: 'recloud', to: '#' },
{ title: 'broker', to: '#' },
{ title: 'mercury', to: '#' },
{ title: 'investor', to: '#' }
],
open: false
}
];
PS I'm new to JS, sorry if I'm misunderstanding something trivial. PS我是JS的新手,如果我误解了一些琐碎的事情,对不起。
Does this accomplish what you're trying to do?:这是否完成了您想要做的事情?:
// Gets array (but you can get it any way you want, maybe by `import`) const subItems = getSubItems(); // Loops through array (using `subItem` as the name for each array element) for(subItem of subItems){ // Destructures the current element in array (using `{...}` for objects) const {links, open} = subItem; // Collects links info (This is not needed -- just makes nicer printing) const linkString = links.reduce( (linkStr, link) => linkStr + `title:${link.title}, to:${link.to}; `, "" ); // Does something with links and open (We could print `links` instead of linkString) console.log("links: ", linkString, "\nopen: ", open, "\n\n"); } function getSubItems(){ return [ { links: [ { title: 'ret', to: '#' }, { title: 'def', to: '#' }, { title: 'rev', to: '#' }, { title: 'red', to: '#' }, { title: 'im', to: '#' }, { title: 'glossar', to: '#' } ], open: true }, { links: [ { title: 'recloud', to: '#' }, { title: 'broker', to: '#' }, { title: 'mercury', to: '#' }, { title: 'investor', to: '#' } ], open: false } ]; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.