如何解决如何解构这个对象数组
我正在尝试对 subItems
数组的元素使用解构来获取直接引用 links
和 open
属性的变量。
具体来说,我正在尝试使用以下代码,该代码在注释中指定失败。
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',{ title: 'rev',{ title: 'red',{ title: 'im',{ title: 'glossar',to: '#' }
],open: true
},{
links: [
{ title: 'recloud',{ title: 'broker',{ title: 'mercury',{ title: 'investor',open: false
}
];
附言我是 JS 新手,如果我误解了一些小事,请见谅。
解决方法
这能完成您想要做的事情吗?:
// 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',{ title: 'rev',{ title: 'red',{ title: 'im',{ title: 'glossar',to: '#' }
],open: true
},{
links: [
{ title: 'recloud',{ title: 'broker',{ title: 'mercury',{ title: 'investor',open: false
}
];
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。