在节点js中过滤json数据

时间:2018-07-31 10:46:43

标签: json node.js

我正在接收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
   }
 ] 

我必须过滤数据,以便仅显示以下键值对

sku
qty

预期结果将是

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

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

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

有什么解决方案可以过滤这种格式的数据?我可以根据特定值过滤数据,但我希望仅包含两对(sku,qty)的json数据

2 个答案:

答案 0 :(得分:1)

您可以将Select All与数组解构一起使用,以使代码简单明了:

Array.map()

答案 1 :(得分:1)

您可以使用这样的地图来做到这一点:

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; 
});