簡體   English   中英

如何解構這個對象數組

[英]How to make a destructuring of this array of objects

我正在嘗試對我的subItems數組的元素使用解構來獲取直接引用linksopen屬性的變量。
具體來說,我正在嘗試使用以下代碼,如注釋中指定的那樣失敗。

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我是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', 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM