简体   繁体   English

正确插入键值对javascript

[英]insert key value pairs properly javascript

I am working to fix some legacy code. 我正在努力修复一些旧代码。 I have made an example and the results will follow. 我举了一个例子,结果将随之而来。 This is an example of the old array. 这是旧数组的一个示例。

var old = { 1: ['A', 'E', 'I', 'O', 'U'] };

This should be what is returned 这应该是返回的

var expected = { a: 1, e: 1, i: 1, o: 1, u: 1 };

Now if I use this 现在如果我用这个

var ETL = function(){};

ETL.prototype.transform = function(old){
    var array = [];
    for (var variable in old) {
        console.log(variable);
        for(var i = 0; i < old[variable].length; i++){
            var obj = {};
            var key = old[variable][i].toLowerCase();
            obj[key] = parseInt(variable);
            array.push(obj);
        }
    }
    return array;
};

I get this result 我得到这个结果

[ { a : 1 }, { e : 1 }, { i : 1 }, { o : 1 }, { u : 1 } ]

Which is really close but not quite what I'm looking for. 这真的很接近,但与我要找的东西不完全相同。 I think I've created an array of objects when I really just want an object with key value pairs. 当我真的只想要一个具有键值对的对象时,我想我已经创建了一个对象数组。 I think step 1 is to redeclare array as an object, and then step 2 is to rework the code to work with an object instead of an array. 我认为第1步是将数组重新声明为对象,然后第2步是重新编写代码以使用对象而不是数组。 I'm just not exactly sure how to do that. 我不确定该怎么做。

var obj = {};
for(var i = 0; i < old[variable].length; i++){

            var key = old[variable][i].toLowerCase();
            obj[key] = parseInt(variable);
            //array.push(obj);
        }

Declare obj only once. 仅声明一次obj。 You are creating it in every iteration of loop 您正在循环的每个迭代中创建它

You can use array reduce method to resolve it. 您可以使用数组reduce方法来解决它。

var old = { 1: ['A', 'E', 'I', 'O', 'U'] };
var _getOne = old['1']; //get value of key 1

function getWordCnt(arr){
    return arr.reduce(function(prev,next){
        prev[next] = (prev[next] + 1) || 1;
        return prev;
    },{});
}
console.log(getWordCnt(_getOne))

Check this jsfiddle 检查这个jsfiddle

Note : Better to have a key as a string instead of an integer 注意:最好将键作为字符串而不是整数

Assuming that your have many properties of the object each with an array of capital letters the following single line assignment will turn them all into the new form. 假设您具有该对象的许多属性,每个属性都带有一个大写字母数组,那么以下单行分配会将它们全部转换为新的形式。

 var old = { 1: ['A', 'E', 'I', 'O', 'U'], 2: ['B', 'T', 'O', 'M', 'V'], 3: ['C', 'B', 'X', 'N', 'S'] }, newList = Object.keys(old).map(k => old[k].reduce((p,c) => {p[c.toLowerCase()] = k*1; return p},{})); document.write("<pre>" + JSON.stringify(newList,null,2) + "</pre>"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM