javascript - I want to take out a certain attribute of the object in an array (objects are placed in it), and then reconstruct it after deduplication. Is there any good way?
大家讲道理
大家讲道理 2017-05-19 10:27:10
0
6
720


It is such an array. I want to take out the value of team_name in each object. After removing the duplicates, form [{"teamName": "value of team_name" ,flag: false},{},{},,,]This form (all flags are false), I thought of the solution (below), I would like to ask if there is any optimization, it is really ugly

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(6)
某草草
function getTeamName(hash){
  return  hash
          .map((value)=>{
                return value.team__name; 
          }).reduce((pre,next)=>{
                if(!pre.some((value)=>{
                    return value === next;
                })){
                    pre.push(next);
                    return pre;
                }else{
                    return pre;
                }
            },[]);
}
阿神
var filters = data.map((item) => item.team_name);
var result = Array.from(new Set(filters))
                  .map(item => {
                       teamName: item,
                       flag: false
                   })
左手右手慢动作

I think the best way to remove duplicates is as follows:

let data = {}       // 判断是否是已经存在的数据
let teamName = []    // 存放结果
for (var item in team_name) {
  if (!data[item]) {    // 如果不存在  添加
    teamName.push({
      teamName: item
    })
  }
  data[item] = 1    // data的item赋值  下次判断的时候  这个值已经有了
}
PHPzhong
const arr = [...new Set(your_data.map(item => item. team_name))].map(item => ({teamName: item, flag: false}))
我想大声告诉你


I changed it to this method in the morning, but when I needed to use the teamList flag later, I found that I had dug a hole for myself, varing a piece of data every time, and then the generated teamList pointer changed, which was harmful. I spent more than two hours and console.log for half a day, and it became clear that it was an object. Finally, I asked the boss to solve the problem. I will record here that when using a third-party library, I wanted to know whether the value or reference was changed. (_.This is a reference to the underscore third-party library)

刘奇

1. First loop and press all the results into an array, and then perform deduplication processing on this array. The disadvantage is that it is verbose.

2. When looping to get the attribute results, make a judgment to see if it is a duplicate, process it to get the final result, and complete it in one loop, fast.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template