How to create jquery array with key values

8.8k Views Asked by At

Is there a way we can create an array in JQuery with key and values? I want to loop through the TFNDailySummaryReportData array and assign its DateWiseSalesData's Name property to key and DateWiseSalesData as value.

for (var i = 0; i < TFNDailySummaryReportData.length; i++) 
{
    var keyValueArray = {
         Key: TFNDailySummaryReportData[i].DateWiseSalesData.Name;
         value: TFNDailySummaryReportData[i].DateWiseSalesData
     }
}

Is it possible to achieve something like this? If yes, how?

2

There are 2 best solutions below

0
On BEST ANSWER

You were very close, You can define an array and use .push() method to populate it.

var arr=[];
for (var i = 0; i < TFNDailySummaryReportData.length; i++) 
{
    arr.push({
         Key: TFNDailySummaryReportData[i].DateWiseSalesData.Name;
         value: TFNDailySummaryReportData[i].DateWiseSalesData
     })
}

You can also use .map()

var arr=TFNDailySummaryReportData.map(function(value){
    return {
         Key: value.DateWiseSalesData.Name;
         value: value.DateWiseSalesData
     }
});
0
On

This has nothing to do with jQuery. Arrays are basic JavaScript, and you can map the KVP based objects to a new array as such:

Using ES6:

const keyValueArray = TFNDailySummaryReportData.map(x => { 
    return { [x.DateWiseSalesData.Name]: x.DateWiseSalesData };
});

Using ES5:

var keyValueArray = TFNDailySummaryReportData.map(function(x) {
    return { x.DateWiseSalesData.Name : x.DateWiseSalesData };
});