将值附加到 javascript 字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19599361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:07:38  来源:igfitidea点击:

Append values to javascript dictionary

javascript

提问by turtle

I am trying to create the following data structure in javascript:

我正在尝试在 javascript 中创建以下数据结构:

d = {"foo": [3, 77, 100], "bar": [10], "baz": [99], "biff": [10]}

My starting data structure is a a list of dictionaries:

我的起始数据结构是一个字典列表:

input = [{"key": "foo", "val": 3}, {"key": "bar", "val": 10}, {"key": "foo", "val": 100}, {"key": "baz", "val": 99}, {"key": "biff", "val": 10}, {"key": "foo", "val": 77]

How can I generate my desired data structure? The following code doesn't seem to append values to the value array.

如何生成所需的数据结构?以下代码似乎没有将值附加到值数组。

var d = {}

for (var i in input) {
    var datum = input[i];
    d[datum.key] = datum.val
}

回答by Barmar

for (var i = 0; i < input.length; i++) {
    var datum = input[i];
    if (!d[datum.key]) {
        d[datum.key] = [];
    }
    d[datum.key].push(datum.val);
}

FYI, you shouldn't use for (var i in input)to iterate over an array.

仅供参考,您不应该使用for (var i in input)迭代数组。

回答by plalx

Another way, with reduce.

另一种方式,与reduce.

var d = input.reduce(function (res, item) {
    var key = item.key;

    if (!res[key]) res[key] = [item.val];
    else res[key].push(item.val);

    return res;

}, {});

回答by techie.brandon

var result = {}
input.forEach(function(keyObject){
  //Make array for key if doesn't exist
  result[keyObject.key] = result[keyObject.key] ? result[keyObject.key] : [];
  //Add value to array
  result[keyObject.key].push(keyObject.val);
});
console.log(result);

回答by gartox

You should be do the next:

你应该做下一个:

for (var i in input){
    var datuml = input[i];    
    if(!d[datuml.key]){
        d[datuml.key]=[];
    }
    d[datuml.key].push(datuml.val);
}

回答by X-Pippes

you will have more then 1 key? Well, I think you want something like convert JSON to ArrayString.

你将有超过 1 把钥匙?好吧,我认为您想要将 JSON 转换为 ArrayString 之类的东西。

Check this Convert JSON To Array Javascriptand this How to convert JSON object to JavaScript array

检查这个将 JSON 转换为数组 Javascript和这个如何将 JSON 对象转换为 JavaScript 数组

etc

等等

回答by wdosanjos

Please try the following:

请尝试以下操作:

        var input = [{ "key": "foo", "val": 3 }, { "key": "bar", "val": 10 }, { "key": "foo", "val": 100 }, { "key": "baz", "val": 99 }, { "key": "biff", "val": 10 }, { "key": "foo", "val": 77 }];
        var d = {};

        for (var i = 0; i < input.length; i++) {
            var entry = input[i];
            if (d[entry.key] === undefined) d[entry.key] = [];
            d[entry.key].push(entry.val);
        }

        alert(JSON.stringify(d));