eslint
一直向我显示prefer-restructing
错误。然而,我并不知道数组破坏是如何工作的,希望能得到一些帮助。
以下是返回错误的两行:
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
}
要获取incategory
的值,您应该按照以下方式使用析构赋值:
null
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);
如果您已经确定数据结构是正确的,且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,它允许您直接设置字。results
而不进行析构:
word.results = word.results.find(
(res) =>
Object.keys(res).includes('partOfSpeech') &&
Object.keys(res).includes('inCategory')
);
下面是基于您的代码的示例:
word.results.inCategory = word.results.inCategory[0];
// and:
word.results = word.results.filter(
// Check if the destructured values are not undefined -> meaning they exist
({partOfSpeech, inCategory}) => partsOfSpeech !== undefined && inCategory !== undefined
)[0];