Skip to content
Advertisement

Return subset of JSON Object using Javascript map() function

My question is if there is a simple way to return a subset of JSON object that will contain all ‘columns’ rather than specifying individually which ‘columns’ to return.

In particular, I have a multi-column csv file converted to JSON. The function below returns a subset of that object – just two ‘columns’ (as another object) if certain condition is met (in this case ‘Name’ is matched):

var firstSubArr = json.map(function(s) {
  if (s.Name === RegName) {
    return {
      'Price': s.Price,
      'Name': s.Name
    }
  }
}).filter(function(n) {
  return n !== undefined
});

Is there a simpler way to return “all columns” from json object as object rather that this:

return {'Price':s.Price,'Name':s.Name}?

Comment: It is just a simple JSON structure after conversion from csv, eg:

`[
    {Name:'Sydney', Price:123, Type:'xyz', etc. 20 more... },
    etc.
    ]`

Comment 2: Yes filter may be an option as a couple of people suggested but what if my condition is a bit more complex, like:

    var fullPeriodArr= json.map( function (s) { 
    if(moment(s.Date,"YYYYMMDD").isSameOrBefore(currd) && moment(s.Date,"YYYYMMDD").isSameOrAfter(fullPeriodStart) && (s.Type==sid || s.Type==sid2)&& s.Name===RegName){return [s.Price, s.Name] 
    }
    }).filter( function (n) { 
    return n!== undefined
    });

SOLUTION:

All 3 respondents provided the clue, thanks! It was just “return every object in the array of objects that matches the condition”, or simply:

    var firstSubArr= json.filter( 

s =>  (moment(s.Date,"YYYYMMDD").isSameOrBefore(currd) && moment(s.Date,"YYYYMMDD").isSameOrAfter(fullPeriodStart) && (s.Type==sid  || s.Type==sid2) && s.Name===RegName)

);

. where time range ‘from… to’ is evaluated using moment.js lib and Date, Type and Name are object keys.

The secret pudding was the round bracket ( ) around the complex condition.

How neat Javascript has become: no need to get .length nor to loop with ‘for’ or ‘while’, no ‘if… else’ statements, or no need to store interim results, and no ‘return’. The arrow replaces all that!

Then you can access eg. Price ‘column’ as array of numbers for summary calculations (eg. sum of values):


var firstSubArrPrice=firstSubArr.map(t => t.Price );

Advertisement

Answer

Get rid of the map() and just use filter() and you will have the original objects in resultant

var firstSubArr = json.filter(function(s) {
  return s.Name === RegName
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement