[英]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];
同樣,我在這方面不是很了解,所以任何關於如何解決/簡化這個問題的幫助都將不勝感激!
編輯:這是一個示例對象供參考:
{
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.inCategory
和word.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.