简体   繁体   中英

How to map this array into a new format with JavaScript

I know there is some functional programming in JavaScript and I am wondering if I can create a function like so using some functional methods easier than just writing the code up myself the procedural way (as you can see below, I am also having some SO formatting issue for some reason).

function mapToFormat(var myarray, var colname) {
}

myarray is actually the following json from a server response...

{
   "time": "1",
   "col1": "2",
   "col2": "3",
   "col3": "1"
},
{
   "time": "2",
   "col2": "3"
},
{
   "time": "3",
   "col1": "3"
},
{
   "time": "4",
   "col3": "3"
},
{
   "time": "5",
   "col1": null
}

I would like to call the function on the above json like so

mapToFormat(myarray, 'col1')

and then have it return data like so (in an array format though)

{
   "time": "1",
   "col1": "2"
},
{
   "time": "3",
   "col1": "3"
},
{
   "time": "5",
   "col1": "null
}

I am thinking maybe I just use var newData = []; $.each(data, function (index, value) { if(value[colname] not exist) { newData.push({ "time": value['time'], colname : value[colname] } }); });

but I am not sure how to tell the difference between "col1" not being there and "col1" : null as I want to pass through any null values that come through as well.

How I can achieve this? And I am wondering if there is a map function or something I should be using that might be better?

Try this (fiddle: http://jsfiddle.net/GNr8N/1/ ):

function mapToFormat(myArray, col) {
 return myArray.map(function(record){
    var result = {
        time: record.time,      
     }
    if (typeof record[col] !== 'undefined') {
     result[col] = record[col]
    }
    return result;
  })
}

The !== operator does not do type casting, so if record[col] exists, it will be added, even if it is null.

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