-1

I have Json Object

0:Object
    $id:"1"
    MetricValue:83
    GeoValue:"EAST"
    DimensionValue:High
    DocCount:28

1:Object
    $id:"2"
    MetricValue:97
    GeoValue:"SOUTH"
    DimensionValue:Medium
    DocCount:28
2:Object
    $id:"3"
    MetricValue:90
    GeoValue:"West"
    DimensionValue:High
    DocCount:30
3:Object
    $id:"4"
    MetricValue:50
    GeoValue:"NORTH"
    DimensionValue:Medium
    DocCount:30

Now i would like to divide this object into two objects based on the MetricValue property,

i.e.

I want group the objects with MetricValue >= 80 into one object and those < 80 into another object.

The above object would be divided into

Object1

0:Object
    $id:"1"
    MetricValue:83
    GeoValue:"EAST"
    DimensionValue:High
    DocCount:28

1:Object
    $id:"2"
    MetricValue:97
    GeoValue:"SOUTH"
    DimensionValue:Medium
    DocCount:28
2:Object
    $id:"3"
    MetricValue:90
    GeoValue:"West"
    DimensionValue:High
    DocCount:30

Object2

0:Object
    $id:"1"
    MetricValue:50
    GeoValue:"NORTH"
    DimensionValue:Medium
    DocCount:30
WorksOnMyLocal
  • 1,617
  • 3
  • 23
  • 44
  • using a loop? What have you tried? On this site we fix bugs with code, not provide complete solutions. And how is it relevant to asp.net MVC? Are you doing this server- or client-side? – ADyson Jul 13 '17 at 10:18

1 Answers1

2

This can be accomplished by using filter and Object.keys().

var arr1 = Object.keys(yourObject).filter(function(obj){
    return obj.metricValue < 91;
});
var arr2 = Object.keys(yourObject).filter(function(obj) {
    return obj.metricValue > 90
});

This will give you two arrays, arr1 containing the objects with metric value less than 91, and arr2 with objects with metric value greater than 90. You can then convert these arrays back into objects, using this code Create object from array

Alternatively you can just loop over the objects properties like this:

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
         // Check metric values here and assign to your new objects
         if(prop.metricValue > 90) // assign to your new object
         else // assign to other object
     } 
 }
CF256
  • 186
  • 1
  • 14