简体   繁体   中英

Convert array to key/value array

Im trying to convert a "simple" array that looks like this:

arr = [143.17, 174.45, 55.3]

To an array of objects in this format:

 Today = new Date();
    newArr =   [ 
        { key: Today, value: 143.17 },
        { key: Today + 1, value: 174.45 },
        { key: Today + 2, value: 55.3}]

Im hoping to create a function to which I can pass the original array and have it return the new one:

objArr = function CreateObjArr(arr){


 return newArr
}

Thank you

You can use the Array.prototype.map function

var newArr = arr.map(function(v, i) {
  return { key: Today + i, value: v };
});

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