过滤数据并映射唯一接收的数据

时间:2018-05-23 08:23:41

标签: javascript angular

我正面临一个问题。

var arr = ['VBH', 'KTL', 'PVC', 'IF & AF', 'BC', 'CC&HC', 'UBS', 'FAD&DVD'];
var obj = [
             {"materialTypeID":9,"name":"","abbreviation":"UBS","count":1,"duns":0,"plantId":0},
             {"materialTypeID":18,"name":null,"abbreviation":"PVC","count":1,"duns":0,"plantId":0},
             {"materialTypeID":7,"name":"","abbreviation":"FAD&DVD","count":4,"duns":0,"plantId":0}
          ];

我希望将结果排序为arr变量显示,如VBH对象或KTL对象(如果找到)。

[       
{"materialTypeID":18,"name":null,"abbreviation":"PVC","count":1,"duns":0,"plantId":0},
{"materialTypeID":9,"name":"","abbreviation":"UBS","count":1,"duns":0,"plantId":0},
{"materialTypeID":7,"name":"","abbreviation":"FAD&DVD","count":4,"duns":0,"plantId":0}
]

在java脚本中,我想实现。

谢谢,

2 个答案:

答案 0 :(得分:0)

您似乎希望通过减少materialTypeID进行排序。

您的问题已在那里得到解决:Javascript object list sorting by object property

obj.sort(function(a, b) { 
    return b.materialTypeID - a.materialTypeID;
})

答案 1 :(得分:0)

循环arr并使用过滤器从obj获取元素。 filter将返回一个新数组,检查这个新数组的长度是否大于0,然后使用push放置元素

var arr = ['VBH', 'KTL', 'PVC', 'IF & AF', 'BC', 'CC&HC', 'UBS', 'FAD&DVD']
var obj = [{
  "materialTypeID": 9,
  "name": "",
  "abbreviation": "UBS",
  "count": 1,
  "duns": 0,
  "plantId": 0
}, {
  "materialTypeID": 18,
  "name": null,
  "abbreviation": "PVC",
  "count": 1,
  "duns": 0,
  "plantId": 0
}, {
  "materialTypeID": 7,
  "name": "",
  "abbreviation": "FAD&DVD",
  "count": 4,
  "duns": 0,
  "plantId": 0
}]

let sortedArray = [];

arr.forEach(function(item) {
  let getElem = obj.filter(function(items) {
    return items.abbreviation === item

  })
  if (getElem.length > 0) {
    sortedArray.push(getElem[0])
  }

})

console.log(sortedArray)