简体   繁体   English

Javascript平面列表到数组连接

[英]Javascript flat list to array concatenation

I am struggling with a particular Javascript problem and I hope someone can help. 我正在努力解决特定的Javascript问题,我希望有人可以提供帮助。

I have a list of name and value pairs, eg: 我有一个名称和值对的列表,例如:

Apple 50 Apple 50
Banana 60 香蕉60
Grape 70 葡萄70
Apple 40 Apple 40
Orange 30 橙色30

I am trying to create a Javascript object out of these values: 我试图用这些值创建一个Javascript对象:

var myObj = {};

and then for all items in the list: 然后列表中的所有项目:

myObj[name] = value;

but as you can see some names are in the list more than once (eg Apple), so in this case I would like to add it to the same property of the object by converting the value in the object to an array and adding the new value to the array. 但是你可以看到一些名字不止一次出现在列表中(例如Apple),所以在这种情况下我想通过将对象中的值转换为数组并添加新的来将它添加到对象的相同属性中数组的值。

So myObj would contain: 所以myObj将包含:

Apple = [50,40] Apple = [50,40]
Banana = 60 香蕉= 60
Grape = 70 葡萄= 70
Orange = 30 橙色= 30

Anyone help? 有人帮吗?

Thanks, 谢谢,

AJ AJ

Like this: 像这样:

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

    if (k in obj) {
        if (obj[k] instanceof Array) {
            obj[k].push(values[i]);
        else
            obj[k] = [ obj[k], values[i] ];
    } else
        obj[k] = values[i];
}

If some of the values are already arrays, they will be flattened, not nested. 如果某些值已经是数组,则它们将被展平,而不是嵌套。

My way. 我的方式。

var MyObj = function(){};
MyObj.prototype.addItem = function(key, val){
    var typ = typeof this[key];
    switch (typ){
        case 'undefined':
            this[key] = val;
            break;
        case 'object':
            this[key].push(val);
            break;
        default:
            this[key] = [this[key], val];
            break;
    }
}

var myObj = new MyObj;

myObj.addItem('Apple', 50);
myObj.addItem('Apple', 70);

console.log(myObj);

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

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