简体   繁体   中英

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

Events: {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()

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/

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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