1

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?

1
  • to check if a value is not there use this if (typeof yourvariable.somevar === "undefined") {} Commented Nov 6, 2013 at 17:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Added the typeof operator to the answer.
In case the undefined value gets overwritten?
Yes. Also because using the typeof operator is the correct way for figuring out the 'type' of javascript objects.
hmmm, this didn't work after all since for the pieces where my column did not exist, it still returned a record with a time and no value which the charting software did not like that much(I need to eliminate those values....I guess back to a each with a push or some kind of for loop but the other stuff helped alot.
Dont' give up yet, ES5 also has a filter function which you might find useful: net.tutsplus.com/tutorials/javascript-ajax/…

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.