【问题标题】:How to simplify using array destructuring如何简化使用数组解构
【发布时间】:2020-12-15 05:38:14
【问题描述】:

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
}

【问题讨论】:

  • 您应该创建一个最小的可重现示例(最好在 codesandbox 上)
  • 您不能使用 destructuring 重新定义对象的属性,这意味着您必须使用两个语句,例如 const { results: { inCategory: [ category ] } } = word; word.results.inCategory = category;
  • 仅供参考,如果您只需要第一次见面,您可以使用find 而不是filter

标签: javascript node.js arrays ecmascript-6 eslint


【解决方案1】:

要获得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')
); 

【讨论】:

  • 谢谢,这两个都很好用!出于好奇,在这种特殊情况下.find().filter() 之间有什么区别吗?
  • @Lioness100 因为你想得到第一个索引而不考虑对象的数量,你可以使用函数find得到第一个匹配。
【解决方案2】:

如果您已经确定您的数据结构是正确的并且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')
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2021-02-23
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多