【问题标题】:how to convert data formats in javascript如何在javascript中转换数据格式
【发布时间】:2018-02-01 04:22:50
【问题描述】:

我正在尝试获取一个段落并将其转换为单词并实现每个单词的频率。

var pattern = /\w+/g,
  string = "mahan mahan mahan yes yes no",
  matchedWords = string.match(pattern);

/* The Array.prototype.reduce method assists us in producing a single value from an
   array. In this case, we're going to use it to output an object with results. */
var counts = matchedWords.reduce(function(stats, word) {

  /* `stats` is the object that we'll be building up over time.
     `word` is each individual entry in the `matchedWords` array */
  if (stats.hasOwnProperty(word)) {
    /* `stats` already has an entry for the current `word`.
       As a result, let's increment the count for that `word`. */
    stats[word] = stats[word] + 1;
  } else {
    /* `stats` does not yet have an entry for the current `word`.
       As a result, let's add a new entry, and set count to 1. */
    stats[word] = 1;
  }

  /* Because we are building up `stats` over numerous iterations,
     we need to return it for the next pass to modify it. */
  return stats;

}, {})

var dict = []; // create an empty array
// this for loop makes a dictionary for you
for (i in counts) {
  dict.push({
    'text': i
  });
  dict.push({
    'size': counts[i]
  });

};

/* lets print and see if you can solve your problem */
console.log(dict);

dict 变量返回:

[ { text: 'mahan' },{ size: 3 },{ text: 'yes' },{ size: 2 },{ text:'no'},{ size: 1 } ]

但我使用的是数据可视化代码,我需要将结果变成这样的:

[ { "text": "mahan" , "size": 3 },{ "text: "yes", size: 2 },{ "text":'no', "size": 1 } ]

我知道这是基本的,但我只是一个试图为项目使用一些代码的艺术家。感谢您的帮助。

【问题讨论】:

  • 那么不要使用两个单独的对象:push({text:i,size:counts[i]})

标签: javascript arrays string object properties


【解决方案1】:

简单地做:

dict.push({'text':i, "size": counts[i]});

【讨论】:

    【解决方案2】:

    您的问题是您要在数组中推送两个不同的对象,以解决您只需要推送一个对象,如 cmets 中所述。

    您可以在Object.keys(counts) 上使用.map() 以更好的方式来代替for loop

    var dict = Object.keys(counts).map(function(k){
        return {text: k, size: counts[k]};
    });
    

    演示:

    var pattern = /\w+/g,
        string = "mahan mahan mahan yes yes no",
        matchedWords = string.match( pattern );
    
    var counts = matchedWords.reduce(function ( stats, word ) {
        if ( stats.hasOwnProperty( word ) ) {
            stats[ word ] = stats[ word ] + 1;
        } else {
            stats[ word ] = 1;
        }
        return stats;
    }, {})
    
    
    var dict = Object.keys(counts).map(function(k){
        return {text: k, size: counts[k]};
    });
    
    console.log(dict);

    【讨论】:

      【解决方案3】:

      您还可以并行构建哈希表(作为 Map)和生成的数组,这可能会更快:

      let pattern = /\w+/g,
        string = "mahan mahan mahan yes yes no",
        matchedWords = string.match(pattern);
      
      let hash = new Map(), result = [];
      
      matchedWords.forEach( word => {
        if(hash.has(word)){
          hash.get(word).size++;
        }else{
          var tmp = { text: word, size: 1};
          hash.set(word,tmp);
          result.push(tmp);
        }
      });
      

      Try it

      【讨论】:

      • 谢谢。上面的任何代码都支持 rtl 语言吗?尝试时遇到“matchedWords 为空”
      • @mahanmeh 可能正则表达式在从左到右的语言中失败。我的代码也可以工作。
      【解决方案4】:

      每次迭代都推送两个对象。不要那样做。要修复您的代码,请执行@asdf_enel_hak 建议的in his answer,如果您想简化代码,您可以更轻松地使用更少的代码。

      let pattern = /\w+/g,
        string = "mahan mahan mahan yes yes no",
        matchedWords = string.match(pattern);
      
      let res1 = [...matchedWords.reduce((a, b) => a.set(b, (a.get(b) || 0) + 1), new Map)].map(e => ({
        text: e[0],
        size: e[1]
      }));
      
      console.log(res1);

      【讨论】:

      • 谢谢,我很难理解你做了什么。但它也很完美。
      • 数组映射到二维数组到对象数组应该更快? (如果你声称它,证明它......)
      • @Jonasw 编辑回答以更好地反映我的意思...不确定它在性能方面是否更快,但写起来肯定更快... :)
      【解决方案5】:

      这与实际问题相当相切,但是您可以将其浓缩很多。下面的例子基本上和刚刚压缩的一样,我使用了Tagged Template Literal 来增加一些额外的语法糖。

      const frequency = s => s[0].match(/\w+/g).reduce((m, e) => ((m[e]=(m[e]||0)+1),m), {});
      
      console.log(frequency`
      Hello foo bar world!
      Hello zoo bar world!
      Hello foo car world!
      Hello foo bar forld!
      `);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-25
        • 1970-01-01
        • 2014-11-22
        • 1970-01-01
        • 2017-12-27
        • 2017-05-11
        • 2018-07-14
        • 1970-01-01
        相关资源
        最近更新 更多