以优化方式进行JSON操作

时间:2019-03-26 06:19:41

标签: javascript

有一个带有名称和技能字段的JSON作为对象数组,如何操作此JSON?

我正在创建新的具有独特技能的Array Unique,并将其与认可数组的所有技能价值进行比较,以某种方式我没有得到解决方案,为此我正在寻找幼稚和优化的解决方案。

let endorsement = [
  { name: 'James', skill: 'JS' },
  { name: 'steve', skill: 'CSS' },
  { name: 'BOB', skill: 'JS' },
  { name: 'jack', skill: 'HTML' },
  { name: 'bob', skill: 'CSS' },
  { name: 'john', skill: 'JS' }

]
//expected Array = [
// {skill : 'JS , people : ['James','BOB','john'],count : 3},
// {skill : 'HTML , people : ['jack'] , count : 1},
// {skill : 'CSS , people : ['steve' ,'bob] , count : 2}
//]


let skillArray = [...endorsement];

const skillsList = skillArray.map(item => item.skill);
let Unique = [... new Set(skillsList)];
const SkillSet = [];
skillsList.map(item => {
  const newObj = {
    skill: '',
    people: [],
    count: 0
  }
  Unique.map(value => {
    if (value === item) {
      newObj.skill = value;
      newObj.people.push(item.name);
      newObj.count += 1;

    }
    delete value;
    SkillSet.push(newObj);
    delete newObj;
  })
})

console.log(SkillSet);

2 个答案:

答案 0 :(得分:0)

如果您想按技能对姓名分组:

let endorsements = [
  { name: 'James', skill: 'JS' },
  { name: 'steve', skill: 'CSS' },
  { name: 'BOB', skill: 'JS' },
  { name: 'jack', skill: 'HTML' },
  { name: 'bob', skill: 'CSS' },
  { name: 'john', skill: 'JS' }
];

let unique = {};

endorsements.forEach(endorsement => {
  unique[endorsement.skill] = unique[endorsement.skill] ? unique[endorsement.skill].push(endorsement.name): [endorsement.name]
})

/*
unique becomes

{
  JS: ['James', 'BOB', 'john'],
  CSS: ['steve', 'bob'],
  HTML: ['jack']
}
*/

答案 1 :(得分:0)

let endorsement = [
    { name: 'James', skill: 'JS' },
    { name: 'steve', skill: 'CSS' },
    { name: 'BOB', skill: 'JS' },
    { name: 'jack', skill: 'HTML' },
    { name: 'bob', skill: 'CSS' },
    { name: 'john', skill: 'JS' }
]

res = endorsement.reduce((acc, val) => {
    const { name, skill } = val
    found = acc.find(e => e.skill === skill)
    if (found) {
        found.people.push(name)
        found.count = found.count += 1
    } else {
        acc.push({ skill, people: [name], count: 1 })
    }
    return acc
}, [])


console.log(res)