提问者:小点点

如何简化使用数组析构


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
}

共3个答案

匿名用户

要获取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.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,它允许您直接设置字。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];