json 我怎样才能更好地编写这份报告候选人功能?

ulmd4ohb  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(162)

这是名为candidatesArray的数组中的输入数据:

[ 
 {"name":"george","languages":["php","javascript","java"],"age":19,"graduate_date":1044064800000,"phone":"32-991-511"},
 {"name":"anna","languages":["java","javascript"],"age":23,"graduate_date":1391220000000,"phone":"32-991-512"},
 {"name":"hailee","languages":["regex","javascript","perl","go","java"],"age":31,"graduate_date":1296525600000,"phone":"32-991-513"}
]

字符串
我需要在这个集合中进行转换,作为函数的结果:

{candidates: [
    {name: "George", age: 19, phone: "32-991-511"},
    {name: "Hailee", age: 31, phone: "32-991-513"},
    {name: "Anna", age: 23, phone: "32-991-512"}
],
languages: [
    {lang:"javascript",count:1}, 
    {lang:"java", count:2}, 
    {lang:"php", count:2}, 
    {lang:"regex", count:1}
]}


函数repCandidates:
第一个月

  • 我需要用JavaScript ES6编写它
  • 我不应该使用循环(for,while,repeat),但foreach是允许的,如果我使用“reduce”函数会更好
  • 应聘者应填写姓名、年龄和电话,并按毕业日期填写。
  • 语言应按字母顺序返回其计数器。

请访问https://codepen.io/rillervincci/pen/NEyMoV?editors=0010查看我的代码。

ocebsuys

ocebsuys1#

一种选择是先将reduce放入candidates子对象,然后将pushlangauges分别放入数组。
迭代后,对candidates进行排序,并从每个候选对象中删除graduate_date属性,然后再次使用reducelanguages数组转换为按语言索引的数组,每次递增count属性:

const input = [{
  "name": "george",
  "languages": ["php", "javascript", "java"],
  "age": 19,
  "graduate_date": 1044064800000,
  "phone": "32-991-511"
}, {
  "name": "anna",
  "languages": ["java", "javascript"],
  "age": 23,
  "graduate_date": 1391220000000,
  "phone": "32-991-512"
}, {
  "name": "hailee",
  "languages": ["regex", "javascript", "perl", "go", "java"],
  "age": 31,
  "graduate_date": 1296525600000,
  "phone": "32-991-513"
}];


const output = input.reduce((a, { languages, ...rest }) => {
  a.candidates.push(rest);
  a.languages.push(...languages);
  return a;
}, { candidates: [], languages: [] });

output.candidates.sort((a, b) => a.graduate_date - b.graduate_date);
output.candidates.forEach(candidate => delete candidate.graduate_date);

output.languages = Object.values(
  output.languages.reduce((a, lang) => {
    if (!a[lang]) a[lang] = { lang, count: 0 };
    a[lang].count++;
    return a;
  }, {})
);
output.languages.sort((a, b) => a.lang.localeCompare(b.lang));

console.log(output);

字符串

pdkcd3nj

pdkcd3nj2#

通常的做法是在reduce()中完成所有的事情,但是有时候如果你把它分解一点会更容易阅读。这会创建一个counter对象作为帮助器来跟踪语言计数。map() s在数组上提取语言和个人信息,然后把它们放在一起:

let arr = [ {"name":"george","languages":["php","javascript","java"],"age":19,"graduate_date":1044064800000,"phone":"32-991-511"},{"name":"anna","languages":["java","javascript"],"age":23,"graduate_date":1391220000000,"phone":"32-991-512"},{"name":"hailee","languages":["regex","javascript","perl","go","java"],"age":31,"graduate_date":1296525600000,"phone":"32-991-513"}]
 
let lang_counter = {
  // helper keeps counts of unique items
  counts:{},
  add(arr){
     arr.forEach(item => this.counts[item] = this.counts[item] ? this.counts[item] + 1 : 1)
  },
  toarray(){
    return Object.entries(this.counts).map(([key, val]) => ({[key]: val}))
  }
}

// iterate over object to create candidates 
let candidates = arr.map(row => {
  let {languages, ...person} = row
  lang_counter.add(languages)  // side effect
  return person
})

// put them together
console.log({candidates, languages:lang_counter.toarray()})

字符串

mxg2im7a

mxg2im7a3#

您可以像下面这样使用Array.reduceObject.values

let arr = [{"name":"george","languages":["php","javascript","java"],"age":19,"graduate_date":1044064800000,"phone":"32-991-511"},{"name":"anna","languages":["java","javascript"],"age":23,"graduate_date":1391220000000,"phone":"32-991-512"},{"name":"hailee","languages":["regex","javascript","perl","go","java"],"age":31,"graduate_date":1296525600000,"phone":"32-991-513"}]


let res = arr.reduce((o, {name, age, phone, graduate_date, languages}) => {
    o.candidates.push({name, age, phone, graduate_date})
  
    languages.forEach(l => {
      o.languages[l] = o.languages[l] || { lang:l, count: 0 }
      o.languages[l].count++
    })
  
    return o
  }
 , { candidates: [], languages: {}})

res.candidates = res.candidates.sort((a,b) => a.graduate_date - b.graduate_date)
                               .map(({ graduate_date, ...rest }) => rest)

res.languages = Object.values(res.languages).sort((a,b) => a.lang.localeCompare(b.lang))
  
console.log(res)

字符串

lawou6xi

lawou6xi4#

如果您不想仅仅使用普通的JavaScript,我可以提供一个直观的解决方案。

import { TrueSet } from "@ut8pia/classifier/queue/TrueSet.js";
import { ORDER } from "@ut8pia/classifier/global.js";
import assert from "assert";

const 
    data = [ 
        {"name":"George","languages": "php","javascript","java"],"age":19,"graduate_date":1044064800000,"phone":"32-991-511"},
        {"name":"Anna","languages":["java","javascript"],"age":23,"graduate_date":1391220000000,"phone":"32-991-512"},
        {"name":"Hailee","languages":["regex","javascript","perl","go","java"],"age":31,"graduate_date":1296525600000,"phone":"32-991-513"}
    ],

    expected = {
        candidates: [
            {name: "George", age: 19, phone: "32-991-511"},
            {name: "Hailee", age: 31, phone: "32-991-513"},
            {name: "Anna", age: 23, phone: "32-991-512"}
        ],

        languages: [
            {lang: "go", count: 1},
            {lang: "java", count: 3}, 
            {lang: "javascript", count: 3}, 
            {lang: "perl", count: 1}, 
            {lang: "php", count: 1}, 
            {lang: "regex", count: 1}
        ]
    };

字符串
要定义你的report(data)函数,你只需要representation函数和TrueSet。请参考@ut8pia/classifier库的解释。
候选人由他们的毕业日期表示,而语言是自我表示的。TrueSet一致地记录每个项目的出现频率,并提供方法n(item)来检索它们。将您的数据添加到TrueSets就是所需的全部。

function report(data) {

    const
        candidates = TrueSet.of(candidate => candidate.graduate_date, ORDER.ASCENDING, ORDER.INSERTION)
            .letAll(data),
        languages = new TrueSet(language => language)
            .letAll(data
                    .map(candidate => candidate.languages)
                        .flat());
    return {
        candidates: candidates 
            .toArray()
                .map(candidate => ({name: candidate.name, age: candidate.age, phone: candidate.phone})),

        languages: languages
            .toArray()
                .map(language => ({lang: language, count: languages.n(language)}))
    }
}


您可以通过以下方式验证结果:

const got = report(data);

assert.deepEqual(got, expected);

相关问题