0

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;
 }
musically_ut
34.3k9 gold badges98 silver badges110 bronze badges
asked Mar 31, 2016 at 11:08

2 Answers 2

2

You can use Array.prototype.map()

Try like this

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

DEMO

answered Mar 31, 2016 at 11:11
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Mar 31, 2016 at 12:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.