根据相似的值将对象拆分为对象数组

时间:2018-08-16 16:05:41

标签: javascript

var pr = {
    name: "ball",
    race: "ball",
    weapon: "axe",
};

var save=new Object;
var keys=Object.keys(pr);

for(var k in pr) { 

}
console.log(save); // should end up with {name:'ball',race:'ball'}

4 个答案:

答案 0 :(得分:1)

如果我对问题的理解正确,那么一个选择是:

const keys = Object.keys(pr);
const ret = keys.reduce((ret, k, i) => {
  const f = keys.find((k2, i2) => i !== i2 && pr[k] === pr[k2]);
  if (f) ret[k] = pr[k];
  return ret;
}, {});

答案 1 :(得分:0)

这是我想出的。

var pr = {
  name: "ball",
  race: "ball",
  weapon: "axe"
};

const dupValues = Object.values(pr).reduce(
  (acc, cur) => ({ ...acc, [cur]: (acc[cur] || 0) + 1 }),
  {}
);

const result = Object.keys(pr)
  .filter(key => dupValues[pr[key]] > 1)
  .reduce((acc, curr) => ({ ...acc, [curr]: pr[curr] }), {});

console.log(result);
// {name:'ball',race:'ball'}

答案 2 :(得分:0)

一种实现方法是将save对象用作直方图,并跟踪重复项。然后,使用reduce过滤掉计数为0的所有键。它应该比像find这样的线性函数具有更好的性能:

var pr = {
  name: "ball",
  race: "ball",
  weapon: "axe"
};
var save = {};

for (var k in pr) {
  save[pr[k]] = pr[k] in save ? save[pr[k]] + 1 : 0;
}

var result = Object.keys(pr).reduce((a, e) => {
  if (save[pr[e]]) { a[e] = pr[e]; }
  return a;
}, {});

console.log(result);

答案 3 :(得分:0)

有效。简单明了。参考文献:Array.reduce()

遍历每个键值对,并累积结果,直到循环结束。

var pr = {
    name: "ball",
    race: "ball",
    weapon: "axe",
    item:"bat",
    newitem:"bat",
    newweapon: "axe"
};

var result = Object.keys(pr).reduce(function(acc, key){
    var ispresent = false;
    acc.forEach(function(obj,i){
        if(ispresent) return;
        if(Object.values(obj)[0]===pr[key])
        {
            obj[key]=pr[key];
            ispresent = true;
        }
    });
    if(!ispresent)
    {
        var newobj = {};newobj[key]=pr[key];
        acc.push(newobj)
    }
    return acc;
},[])

console.log(result)