[英]How do I return an associative array key as string?
I have an array that is set up as follows 我有一个数组,设置如下
var myArray = [
{'10/3/2014': "some value"},
{'10/4/2014': "some value"},
{'10/5/2014': "some value"}];
This is a simple version of the data I need, and I am able to access the values in the array just as I would expect. 这是我需要的数据的简单版本,并且能够像我期望的那样访问数组中的值。
My Question: How can I use the key value as a string? 我的问题:如何将键值用作字符串? I would like to be able to use the date I am using as a key in other places for display purposes. 我希望能够将我正在使用的日期用作其他地方的键,以用于显示。
Edit for more specifics about question 编辑有关问题的更多详细信息
I have json data as follows 我有JSON数据如下
Events: {10/3/2014: [{}],10/4/2014: [{},{}],10/5/2014: [{},{}]} 活动:{10/3/2014:[{}],10/4/2014:[{},{}],10/5/2014:[{},{}]}
each date represents has an array with one or more event details (actual data is removed so you can get the idea without taking up more room). 每个日期代表一个包含一个或多个事件详细信息的数组(实际数据已删除,因此您无需花费更多空间就可以得到创意)。 I iterate through the items and use them as I would expect but I would like to use the dates and do not know how to access them. 我遍历所有项目并按预期使用它们,但是我想使用日期,但不知道如何访问它们。
Just set it up as an object like: 只需将其设置为如下对象:
var myVar = { '10/3/2014': "some value", '10/4/2014': "some value", '10/5/2014': "some value"};
Then you can call it like 然后你可以这样称呼它
alert(myVar['10/3/2014']);
I you want to create an object map out of your array where they keys are the dates, here's one way of doing it: 我想从数组中创建一个对象映射,其中键为日期,这是一种方法:
var myArray = [
{'10/3/2014': "some value"},
{'10/4/2014': "some value"},
{'10/5/2014': "some value"}
];
var valuesMap = myArray.reduce(function (map, obj) {
var date = Object.keys(obj).pop();
map[date ] = obj[date];
return map;
}, {});
//{10/3/2014: "some value", 10/4/2014: "some value", 10/5/2014: "some value"}
Try using Object.keys() 尝试使用Object.keys()
Example: 例:
var myArray = [{ '10/3/2014': "some value"}, {'10/4/2014': "some value"}, {'10/5/2014': "some value"}];
Object.keys(myArray[0])[0]; // will return '10/3/2014'
Object.keys(myArray[1])[0]; // will return '10/4/2014'
Object.keys(myArray[2])[0]; // will return '10/5/2014'
Hope this helps! 希望这可以帮助!
I would do something like that with the help of an array : http://jsfiddle.net/csdtesting/et1m795a/ 我会在数组的帮助下做类似的事情: http : //jsfiddle.net/csdtesting/et1m795a/
var myArray = [{ '10/3/2014': "some value" }, { '10/4/2014': "some value" }, { '10/5/2014': "some value" }]; var splashArray = new Array(); //the array with the key names $.each(myArray, function(key, value) { $.each(value, function(key, value) { //console.log(key, value); splashArray.push(key); }); }); document.write(splashArray[0]) /*10/3/2014*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.