3

Had generated one json array using the filter.

orders = filterFilter(vm.gridOptions.data, {
                                sampleId: 295
                        });

Here I filtered my orders array and I got this.

{
  "orders": [
    {
      "orderId": 51491,
      "orderDate": "2016-12-19T13:35:39",
      "regId": 1354,
      "sampleId": 295,
      "name": "Test",
      "nameAr": "Test"
    },
    {
      "orderId": 51493,
      "orderDate": "2016-12-19T13:35:39",
      "regId": 1354,
      "sampleId": 295,
      "name": "Test",
      "nameAr": "Test",

    }
  ]
}

Can I filter in way, It should keep only one field in the orders array. Using angular filter I need to do this.

I need an array like this.

{
  "orders": [
    {
      "orderId": 51491
    },
    {
      "orderId": 51493
    }
  ]
}
1
  • No, not using angular's filter filter. It filters. It doesn't map. But Array.map() is your friend (and Array.filter(), too, BTW). Commented Dec 20, 2016 at 7:39

3 Answers 3

6

When you need to transform object to another, use Array.map() method. You can use it together with Array.filter() method to filter results.

orders = vm.gridOptions.data
    .filter(function (x) {
        return x.sampleId === 295;
    })
    .map(function (x) {  
        return {
            orderId: x.orderId
        };
    });

The above function returns an array of objects that contain only orderId property and sampleId is equal to 295.

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

Comments

1

Alternatively, You can iterate through the orders to generate the array of objects having orderIds. Like this,

$scope.orderIDs = [];
angular.forEach($scope.orders, function(order){
    $scope.orderIDs.push({
        "orderId": order.orderId
    })
});

Comments

0

I followed @Jarek answer above and implemented in my code: In my case, I had an array of file names with other details but I wanted to reduce it only names. So I first filtered array that has names begins with "sharath/subDir/12345678-"

filesList.filter(t => t.name.startsWith("sharath/subDir/123456789-")).map(x => {return x.name})

Hope it might help someone.

Comments

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.