简体   繁体   中英

How to add each array element into aN array?

By using JS, I am trying to get a 2d array where I have an array as shown below :

   array [ "2016/03/31", "2016/03/30", "2016/03/29", "2016/03/28", "2016/03/27", "2016/04/01"]

Looking for output as

    array [
         {'date':'2016/03/22'},  
         {'date':'2016/03/23'},
         {'date':'2016/03/24'},
         {'date':'2016/03/25'},
         {'date':'2016/03/26'},
         {'date':'2016/03/27'},   
         {'date':'2016/03/28'},
         {'date':'2016/03/29'}
       ];

JS

    function getarryDates (list)
    {
        var aryDates = [];
        var Dates_ary = [];
        $.each(list, function(i, e) {              
              Dates_ary[0] =       aryDates.push("'date:'"+ e);  
        });
        return Dates_ary;
     }

You can use Array.prototype.map()

Try like this

var newList=list.map(function(x){ return {'date':x} })

DEMO

If you want to do it with minimal changes, you can do this:

function getarryDates (list)
{
    var aryDates = [];
    var Dates_ary = [];
    $.each(list, function(i, e) {              
          Dates_ary[i] = {"date": e };  // <-- use index 'i' and 
                                        // create object instead of str.
    });
    return Dates_ary;
 }

However, the solution with map is better: it is DRY, easier to understand and easier to maintain.

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