如何根据条件在对象的属性周围随机播放

时间:2019-02-19 21:34:23

标签: javascript object

JSBin: https://jsbin.com/kuwivohixu/edit?html,js,output

var v = {
    checkit: {
    'company_dummy': {
        count: 0
    },
    'company_2': {
      count: 1
    },
    'company_3': {
      count: 1
    },
    'company_4': {
      count: 6
    },
    'company_5': {
      count: 6
    }
  }
}

var newest_company = "company_5";
var company_sorted = [];
for (var each_company in v['checkit']) { //for each company in 'v'
  company_sorted.push([each_company, v['checkit'][each_company]]); //save the company and the company object in affinity
}

company_sorted.sort(function(a, b) {
  return b[1]['count'] - a[1]['count'];
});

/*
company_sorted.sort(function(a,b) {
  //How can I update my object that if the `newest_company` has a count
    that is tied with another company as the higest `count` then move 
    that to be the first in the group after being sorted from high to low

})
*/

console.log('company_dummy' in v['checkit']);
console.log(company_sorted);

如果newest_company有计数,我如何更新我的对象         与另一家公司捆绑在一起,成为最高count,然后移动         从高到低排序之后,成为该组中的第一名

2 个答案:

答案 0 :(得分:0)

如果计数相等,则可以将公司与所需公司进行比较:

/* v (bad name) and newest exist */
const companies = Object.entries(v.checkit);

companies.sort(([nameA, objA], [nameB, objB]) => 
 objB.count - objA.count ||
 (nameA === newest_company) - (nameB === newest_company)
);

答案 1 :(得分:0)

像这样使用Object.keys

let companies = []
Object.keys(v.checkit).forEach(c => {
   if (c !== newest_company)
      companies.push({name: c, count: v.checkit[c].count})
})
companies.sort((a, b) => { return b.count - a.count})
for (let i = 0; i < companies.length; i++) {
   if (v.checkit[newest_company].count >= companies[i].count) {
      companies.splice(i, 0, {name: newest_company, count: v.checkit[newest_company].count})
      break;
   }
}
if (!companies.length) companies.push(v.checkit[newest_company])
v.checkit = companies

NB:此解决方案将您的Checkit正确性转换为数组