簡體   English   中英

如何使用數組解構來簡化

[英]How to simplify using array destructuring

eslint不斷向我展示一個prefer-restructuring錯誤。 但是,我真的不知道數組解構是如何工作的,並且希望得到一些幫助。

這是返回錯誤的兩行:

word.results.inCategory = word.results.inCategory[0];

// and:

word.results = word.results.filter(
 (res) =>
  Object.keys(res).includes('partOfSpeech') &&
  Object.keys(res).includes('inCategory')
)[0];

同樣,我在這方面不是很了解,所以任何關於如何解決/簡化這個問題的幫助都將不勝感激!

eslint 錯誤


編輯:這是一個示例對象供參考:

{
  word: 'midrash',
  results: [{
    definition: '(Judaism) an ancient commentary on part of the Hebrew scriptures that is based on Jewish methods of interpretation and attached to the biblical text',
    partOfSpeech: 'noun',
    inCategory: ['judaism'],
    typeOf: [ 'comment', 'commentary' ]
  },
  { 
    definition: 'something',
    partOfSpeech: 'something',
  }],
  syllables: { count: 2, list: [ 'mid', 'rash' ] },
  pronunciation: { all: "'mɪdrɑʃ" },
  frequency: 1.82
}

如果您已經確定您的數據結構是正確的,並且word.results.inCategoryword.results都是數組,那么您可以這樣做:

const { results:{ inCategory: [inCategory] }} = word;
word.results.inCategory = inCategory;

// and:

const [results] = word.results.filter(
 (res) =>
  Object.keys(res).includes('partOfSpeech') &&
  Object.keys(res).includes('inCategory')
);

word.results = results;

當然,在第二次破壞時,您可以使用 find 直接設置word.results而不破壞:

word.results = word.results.find(
 (res) =>
  Object.keys(res).includes('partOfSpeech') &&
  Object.keys(res).includes('inCategory')
);

要獲得inCategory的值,您應該使用如下解構賦值:

 const obj = { word: 'midrash', results: { definition: '(Judaism) an ancient commentary on part of the Hebrew scriptures that is based on Jewish methods of interpretation and attached to the biblical text', partOfSpeech: 'noun', inCategory: 'judaism', typeOf: [ 'comment', 'commentary' ] }, syllables: { count: 2, list: [ 'mid', 'rash' ] }, pronunciation: { all: "'mɪdrɑʃ" }, frequency: 1.82 } let {results: {inCategory: category}} = obj; //Now you can assign the category to word.results.inCategory console.log(category);

對於過濾器方法,我建議使用函數Array.prototype.find

word.results = word.results.find(
 (res) =>
  Object.keys(res).includes('partOfSpeech') &&
  Object.keys(res).includes('inCategory')
); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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