简体   繁体   中英

Filter json data in node js

I am receiving following data in the form of json

 [{
     "Id": 1,
     "sku": "abc",
     "name": "Abbey Black Round Glass and Chrome 3 Tier Stand",
     "qty": 14
   },
   {
     "Id": 3,
     "sku": "abc",
     "name": "Ammy Black Glass and Chrome 5 Tier Corner Stand",
     "qty": 0
   },
   {
     "Id": 4,
     "sku": "abc",
     "name": "Barcelona Adjustable Gas Lift Black Bar Stool (Set of 2)",
     "qty": 0
   }
 ] 

I have to filter data so that it shows only following key-value pair

sku
qty

Expected result will be

[{
    "sku": "abc",
    "qty": 14
  },
  {

    "sku": "abc",
    "qty": 0
  },
  {

    "sku": "abc",
    "qty": 23
  }
]

Any solution to filter data in such a format?. I can filter data based on specific values but I want json data containing only two pairs (sku,qty)

You can use Array.map() with array destructuring to make your code simple and short:

 var data = [ { "Id": 1, "sku": "abc", "name": "Abbey Black Round Glass and Chrome 3 Tier Stand", "qty": 14 }, { "Id": 3, "sku": "abc", "name": "Ammy Black Glass and Chrome 5 Tier Corner Stand", "qty": 0 }, { "Id": 4, "sku": "abc", "name": "Barcelona Adjustable Gas Lift Black Bar Stool (Set of 2)", "qty": 23 } ]; var res = data.map(({sku, qty}) => ({sku, qty})); console.log(res); 

You can do it with map like this:

var array=[
    {
        "Id": 1,
        "sku": "abc",
        "name": "Abbey Black Round Glass and Chrome 3 Tier Stand",
        "qty": 14
    },
    {
        "Id": 3,
        "sku": "abc",
        "name": "Ammy Black Glass and Chrome 5 Tier Corner Stand",
        "qty": 0
    }];

array.map(function(item) { 
    delete item.Id; 
delete item.name; 
    return item; 
});

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