【问题标题】:Iterating over array and adding unique parameters to new array迭代数组并将唯一参数添加到新数组
【发布时间】:2018-01-17 13:22:11
【问题描述】:

我遇到了一个问题,希望得到有关如何解决的反馈。

这是我的 JSON:

  questions: [
    {
      question: 'lala',
      answer: 'papa',
      categories: ['Handla']

    },
    {
      question: 'xxxx',
      answer: 'yyyy',
      categories: ['Reklamation']
    },
    {
      question: 'abcefg',
      answer: 'gooooogle',
      categories: ['Reklamation']
    }
  ]

我想遍历这个问题数组并将 ALL object.categories 附加到一个新数组,然后过滤掉重复的数组。所以基本上我的回答应该是:

["Handla", "Reklamation"]

【问题讨论】:

  • 根本不是很好的复制品。这是可能的解决方案:const categories = data.questions.reduce((prev, curr) => prev.concat(curr.categories), []).filter((category, index, array) => array.indexOf(category) === index).
  • @dfsq 这比vars cats=[]; for (var i = 0; i < questions.length; i++) { var cat = questions[i].categories[0]; if (cats.indexOf(cat) == -1) cats.push(cat); } 更漂亮、更易读——我眼里含着泪;)

标签: javascript arrays ecmascript-6


【解决方案1】:

感谢 ES6 Set,您可以轻松过滤重复值。您只需先将类别展平为一个数组:

const questions = [
    {
      question: 'lala',
      answer: 'papa',
      categories: ['Handla']

    },
    {
      question: 'xxxx',
      answer: 'yyyy',
      categories: ['Reklamation']
    },
    {
      question: 'abcefg',
      answer: 'gooooogle',
      categories: ['Reklamation']
    }
  ];
const flattened = questions.reduce((prev, curr) => [...prev, ...curr.categories], []); // ['Handla', 'Reklamation', 'Reklamation']
const unique = Array.from(new Set(flattened));
console.log(unique);

【讨论】:

    【解决方案2】:

    您可以使用 map() 方法和 ES6 Set 和扩展语法 ... 来做到这一点

    const data = {"questions":[{"question":"lala","answer":"papa","categories":["Handla"]},{"question":"xxxx","answer":"yyyy","categories":["Reklamation"]},{"question":"abcefg","answer":"gooooogle","categories":["Reklamation"]}]}
    
    const result = [...new Set([].concat(...data.questions.map(o => o.categories)))]
    console.log(result)

    或者代替map(),您可以使用reduce() 并使用Set 作为累加器参数。

    const data = {"questions":[{"question":"lala","answer":"papa","categories":["Handla"]},{"question":"xxxx","answer":"yyyy","categories":["Reklamation"]},{"question":"abcefg","answer":"gooooogle","categories":["Reklamation"]}]}
    
    const result = [...data.questions.reduce((r, e) => {
      return r.add(...e.categories), r
    }, new Set)]
    console.log(result)

    【讨论】:

      【解决方案3】:

      您可以分两步完成。将问题减少到所有类别的数组,然后过滤独特的项目。像这样的:

      const data = {
        questions: [{
            question: 'lala',
            answer: 'papa',
            categories: ['Handla']
      
          },
          {
            question: 'xxxx',
            answer: 'yyyy',
            categories: ['Reklamation']
          },
          {
            question: 'abcefg',
            answer: 'gooooogle',
            categories: ['Reklamation']
          }
        ]
      }
      
      const categories = data.questions
        .reduce((prev, curr) => prev.concat(curr.categories), [])
        .filter((category, index, array) => array.indexOf(category) === index)
      
      console.log(categories)

      【讨论】:

        【解决方案4】:

        您可以将所有类别收集到一个数组中,并使用Set 获取唯一值。

        var questions= [{ question: 'lala', answer: 'papa', categories: ['Handla'] }, { question: 'xxxx', answer: 'yyyy', categories: ['Reklamation'] }, { question: 'abcefg', answer: 'gooooogle', categories: ['Reklamation'] }],
            unique = [...new Set(questions.reduce((r, { categories: c }) => r.concat(c), []))];
          
        console.log(unique);

        【讨论】:

          【解决方案5】:

          您可以在更多浏览器上使用普通的旧 JS

          var cats = [], questions = [{question: 'lala',answer: 'papa',categories: ['Handla']},{question: 'xxxx',answer: 'yyyy',categories: ['Reklamation']},{question: 'abcefg',answer: 'gooooogle',categories: ['Reklamation']}];
          
          for (var i = 0; i < questions.length; i++) {
            var cat = questions[i].categories[0];
            if (cats.indexOf(cat) == -1) cats.push(cat);
          }
          console.log(cats);

          更现代一点:

          const questions = [{question: 'lala',answer: 'papa',categories: ['Handla']},{question: 'xxxx',answer: 'yyyy',categories: ['Reklamation']},{question: 'abcefg',answer: 'gooooogle',categories: ['Reklamation']}];
          let cats = [];
          
          questions.forEach(function(q) {
            var cat = q.categories[0];
            if (cats.indexOf(cat) == -1) cats.push(cat);
          });
          console.log(cats);

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-11-30
            • 1970-01-01
            • 2012-08-27
            • 1970-01-01
            • 2018-01-26
            • 1970-01-01
            • 2022-01-13
            • 2016-02-06
            相关资源
            最近更新 更多