如何在javascript中转换数据格式

时间:2017-08-23 14:07:45

标签: javascript arrays string object properties

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



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 } ]

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

5 个答案:

答案 0 :(得分:3)

简单地做:

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

答案 1 :(得分:1)

每次迭代都要推送两个对象。不要这样做。要修复代码,请执行@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);




答案 2 :(得分:1)

您的问题是您正在推送数组中的两个不同对象,以修复您只需按下注释中提到的一个对象。

而不是使用for loop,您可以使用.map()上的Object.keys(counts)以更好的方式执行此操作:

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

<强>演示:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

你也可以建立一个哈希表(作为Map)和并行生成的数组,这可能会更快:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- CSS -->
<style type="text/css">
/* general */
*, .border-box {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

/* tr.output */
tr.output {
    vertical-align: top;
}

tr.output > td > * {
    width: 100%;
}
</style> 

<!-- HTML -->
<form name="InventoryUp">
<table>
    <tr>
        <td colspan="2" align="center" bgcolor="#97d700">
            <h2>Equipo(s) a ser utilizados</h2>
        </td>
    </tr>
    <tr>
        <td align="center" bgcolor="#D4D4D4"></td>
        <td align="center" bgcolor="#D4D4D4"><b><em>Cantidad (#)</em></b>
        </td>
    </tr>
    <tr>
        <td align="center" bgcolor="#D4D4D4">
            <select id="inventory" size="1">
                <option id="0">Seleccione un equipo</option>
                <option id="abbi5000">ABB Inverter(5000)</option>
                <option id="abbiPVI3.6">ABB Inverter(PVI 3.6)</option>
                <option id="abbiPVI4.2">ABB Inverter(PVI 4.2)</option>
                <option id="bGE20">Breakers(GE 20 AMP)</option>

                <!-- Many more options... -->
            </select>
        </td>
        <td align="center" bgcolor="#D4D4D4">
            <input type="number" id="cantidad" placeholder="Ex: 5" size="1">
        </td>
    </tr>
    <tr class="actions">
        <td colspan="2" align="center" bgcolor="#D4D4D4">
            <!-- Añadir -->
            <input type="button" id="anadir" onclick="anadirEquipo()" value="Añadir" />

            <!-- Retirar -->
            <input type="button" id="retirar" onclick="retirarEquipos()" value="Retirar" />
        </td>
    </tr>
    <tr>
        <th align="center" bgcolor="#2AD2C9">
            <h4>Equipo(s) añadido(s):</h4>
        </th>
        <th align="center" bgcolor="#2AD2C9">
            <h4>Total:</h4>
        </th>
    </tr>
    <tr class="output">
        <td>
            <select type="text" id="equipos" multiple readonly>
            </select>
        </td>
        <td>
            <input type="number" id="quantity" value="0" readonly />
        </td>
    </tr>
</table>
</form>

<!-- JavaScript -->
<script type="text/javascript">
// vars
var pageLoaded = false,
    model = null;

// functions
function anadirEquipo() {
    var cantidad = +document.getElementById('cantidad').value || 1,
        selected = model.inventory.options[model.inventory.selectedIndex],
        choice;

    if (pageLoaded) {
        if (+selected.value !== 0) {
            model.quantity.value = +model.quantity.value + cantidad;

            while (cantidad-- > 0) {
                choice = document.createElement('option');
                choice.text = selected.text;
                choice.value = selected.value;

                model.equipos.add(choice);
            }
        }
    }
}

function retirarEquipos() {
    var options = model.equipos.options,
        i;

    if (pageLoaded) {
        for (i = 0; i < options.length; i) {
            if (options[i].selected) {
                model.equipos.remove(options[i]);
                model.quantity.value--;

            } else {
                i++;
            }
        }
    }
}

// init
window.onload = function() {
    model = {
        inventory: document.getElementById('inventory'),
        equipos: document.getElementById('equipos'),
        quantity: document.getElementById('quantity')
    };

    pageLoaded = true;
};
</script>

Try it

答案 4 :(得分:0)

这与实际问题相当,但你可以将其浓缩一点。下面的例子基本上只是浓缩了,我使用Tagged Template Literal来获得一些额外的语法糖。

rails routes