问题描述
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')
);