2

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?

1
  • keyValuesArray.push("TFNDailySummaryReportData[i].DateWiseSalesData.Name" : "TFNDailySummaryReportData[i].DateWiseSalesData") Commented Dec 29, 2016 at 9:23

2 Answers 2

3

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
     }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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 };
});

Comments

Your Answer

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.