【问题标题】:How to get from an array of objects all unique values of a property that is an array itself如何从对象数组中获取数组本身的属性的所有唯一值
【发布时间】:2018-12-05 11:39:07
【问题描述】:

This answer is already close,并且有一些答案如何在数组中获取唯一值(删除重复项),尽管我无法使其适用于关于对象数组的情况,以及应该的属性被过滤的是一个数组。对不起,我是一个JS新手。感谢您的帮助。

我有一个这样的对象数组

const posts = [
  post1: {
    id: 1,
    title: 'One',
    tags: ['tagA', 'tagB']
    },
  post2: {
    id: 2,
    title: 'Two',
    tags: ['tagB', 'tagC']    
    },
  post3: {
    id: 3,
    title: 'Three',
    tags: ['tagB', tagC, tagD]    
    ]

我需要的是一个包含所有唯一标签的数组......在上面的例子中,预期的输出是这样的:

// [tagA, tagB, tagC, tagD] 

编辑/更新

对象数组中的键用于管理反应组件的状态...例如

constructor(props) {
super(props);

this.state = {
  posts: []
};
}

...

updatePost = (key, updatedPost) => {
//1. Take copy of the current this.state.
const posts = {...this.state.texts};
//2. Update that state
posts[key] = updatedPost;
//3. Set that to state
const options = { encrypt: false }
putFile(postsFileName, JSON.stringify(posts), options)
  .then(() => {
    this.setState({
      posts: posts
    })
  })
  };

【问题讨论】:

  • 您的帖子不是有效的 JS,它应该是您的数组中的直接对象吗?
  • 这不是一个有效的数组。
  • 如果您不明白他们在说什么,posts 是一个数组,post1、post2、post3 将是对象中的键,而不是数组。您是否错误地复制了某些内容?
  • 对不起,伙计们,如果我在这里使用了错误的术语,我们深表歉意。这就是我所说的“对象数组”,是我在添加帖子后在我的反应组件中获得的状态。添加密钥以管理/更新帖子...参见上面的“编辑/更新”。

标签: javascript arrays filter unique


【解决方案1】:

假设输入为[ {} , {} ]格式:

您可以使用concat 和map 来展平您的阵列。使用new Set 获取唯一值。

const posts = [{"id":1,"title":"One","tags":["tagA","tagB"]},{"id":2,"title":"Two","tags":["tagB","tagC"]},{"id":3,"title":"Three","tags":["tagB","tagC","tagD"]}];

var result = [...new Set([].concat(...posts.map(o => o.tags)))];

console.log(result);

如果变量是对象({a:{} , b:{} }),可以使用Object.values将对象转换为数组。

const posts = {"post1":{"id":1,"title":"One","tags":["tagA","tagB"]},"post2":{"id":2,"title":"Two","tags":["tagB","tagC"]},"post3":{"id":3,"title":"Three","tags":["tagB","tagC","tagD"]}}

var result = [...new Set([].concat(...Object.values(posts).map(o => o.tags)))];

console.log(result);

【讨论】:

  • 我想对此表示赞同,但这实际上取决于 OPs 数据集应该是对象还是数组。
【解决方案2】:

您可以reduce您的帖子并遍历标签并将其推送到您尚未遇到的结果:

const posts = [
  {
    id: 1,
    title: "One",
    tags: ["tagA", "tagB"]
  },
  {
    id: 2,
    title: "Two",
    tags: ["tagB", "tagC"]
  },
  {
    id: 3,
    title: "Three",
    tags: ["tagB", "tagC", "tagD"]
  }
];

const uniqueTags = posts.reduce((result, post) => {
  post.tags.forEach(tag => {
    if (!result.includes(tag)) {
      result.push(tag);
    }
  });

  return result;
}, []);

console.log(uniqueTags);

【讨论】:

    【解决方案3】:

    这是假设您知道数组键始终是“标签”。

    let filter = {};
    let result = [];
    
    posts.forEach(post => {
      const tags = post['tags'];
      tags.forEach(tag => {
        if (!filter.hasOwnProperty(tag)) {
          result.push(tag);
          filter[tag] = true; 
        }
      });
    });
    

    【讨论】:

      【解决方案4】:

      使用 jquery 你可以做类似的事情(未测试):

      var results = [];
      $.each(myObject, function(key,valueObj){
          var check.isArray(obj);
          if(check){
              alert(key + "/" + valueObj );
              /*replace repeat*/
              var sorted_check = check.slice().sort(); // You can define the comparing function here. 
                                           // JS by default uses a crappy string compare.
                                           // (we use slice to clone the array so the
                                           // original array won't be modified)
      
              for (var i = 0; i < sorted_check.length - 1; i++) {
                  if (sorted_check[i + 1] == sorted_check[i]) {
                      results.push(sorted_check[i]);
                  }
              }
          }
      });
      

      还有一个使用 indexof 的好方法:

      Array.prototype.unique = function() {
          var a = [];
          for ( i = 0; i < this.length; i++ ) {
              var current = this[i];
              if (a.indexOf(current) < 0) a.push(current);
          }
      
          this.length = 0;
          for ( i = 0; i < a.length; i++ ) {
              this.push( a[i] );
          }
      
          return this;
      }
      
      Array.prototype.unique = function() {
          var a = [];
          for ( i = 0; i < this.length; i++ ) {
              var current = this[i];
              if (a.indexOf(current) < 0) a.push(current);
          }
          return a;
      }
      

      并跟进:

      Array.prototype.unique = function(mutate) {
          var unique = this.reduce(function(accum, current) {
              if (accum.indexOf(current) < 0) {
                  accum.push(current);
              }
              return accum;
          }, []);
          if (mutate) {
              this.length = 0;
              for (let i = 0; i < unique.length; ++i) {
                  this.push(unique[i]);
              }
              return this;
          }
          return unique;
      }
      

      【讨论】:

        【解决方案5】:

        如果你想使用像Ramda.js 这样的函数库,你可以这样做:

        const posts = [
        	{
        		id: 1,
        		title: 'One',
        		tags: ['tagA', 'tagB'],
        	},
        	{
        		id: 2,
        		title: 'Two',
        		tags: ['tagB', 'tagC'],
        	},
        	{
        		id: 3,
        		title: 'Three',
        		tags: ['tagB', 'tagC', 'tagD'],
        	},
        ];
        
        var unique = R.uniq(R.flatten(R.map(R.prop('tags'), posts)))
        console.log(unique)
        &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"&gt;&lt;/script&gt;

        【讨论】:

          猜你喜欢
          • 2017-01-07
          • 2018-11-14
          • 2018-05-25
          • 1970-01-01
          • 2019-10-20
          • 2020-09-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多