繁体   English   中英

如何使用数组解构来简化

[英]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];

同样,我在这方面不是很了解,所以任何关于如何解决/简化这个问题的帮助都将不胜感激!

eslint 错误


编辑:这是一个示例对象供参考:

{
  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.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')
);

要获得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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM