javascript 使用javascript将数组值添加到地图中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24385115/
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
Add array values into map using javascript?
提问by Maniram
I have an array value as a with key:value pair. I wanted to map the same key array values as below format:
我有一个带有键:值对的数组值。我想映射与以下格式相同的键数组值:
Expected Output: [abc: 1],[def:2,42,40]
Please find my code below:
请在下面找到我的代码:
var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
var array_keys = new Array();
var array_values = new Array();
for (var key in a) {
array_keys.push(key);
array_values.push(a[key]);
}
alert(array_keys);
alert(array_values);
It returns the values as
它返回值作为
My output : [abc:def] [1,40]
Any help on this?
有什么帮助吗?
采纳答案by Andy
You can achieve something like what you want if you play around with your initial data structure:
如果您使用初始数据结构,您可以实现类似的目标:
Have an array of objects:
有一个对象数组:
var a = [{abc: 1}, {def: 2}, {def: 42}, {def: 40}];
Set up a new object
设置一个新对象
var o = {};
And then loop over the data. For each object: if the key doesn't exist in o
, the output object, add it and set its value to an array, otherwise just push the value of the object to the array.
然后循环遍历数据。对于每个对象:如果键o
在输出对象中不存在,则添加它并将其值设置为数组,否则只需将对象的值推送到数组。
for (var i = 0, l = a.length; i < l; i++) {
var key = Object.keys(a[i]);
if (!o[key]) { o[key] = []; }
o[key].push(a[i][key]);
}
And you end up with an object the values of which are arrays:
你最终得到一个对象,其值是数组:
console.log(o); // {abc: [1], def: [2,42,40] }
回答by Michael Kunst
var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
This is not possible. Object keys must be unique in javascript, so you can't add 3 different items with the same key ("def"). If you define multiple elements with the same key, at least chrome will take the lastadded value.
这不可能。对象键在 javascript 中必须是唯一的,因此您不能使用相同的键(“def”)添加 3 个不同的项目。如果你用相同的键定义了多个元素,至少 chrome 会取最后一个添加的值。
So answering your question: With the input provided there is no way to get you Expected output.
所以回答你的问题:通过提供的输入,无法获得预期的输出。