簡體   English   中英

jQuery / JavaScript:使用另一個數組過濾數組

[英]jQuery/JavaScript: Filter array with another array

假設我有兩個數組:

{First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two, Three]}

[First, Third]

現在,我需要刪除第一個數組中不在第二個數組中的每個鍵。 所以-在這兩個例子中-我應該留下:

{First: [One, Two, Three], Third: [One, Two, Three]}

我試圖為此使用$ .grep,但是我不知道如何使用數組作為過濾器。 需要幫助! :)

最快的方法是創建一個新對象,僅復制所需的鍵。

var obj = {First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two, Three]}
var filter = {First: [One, Two, Three], Third: [One, Two, Three]}


function filterObject(obj, filter) {
  var newObj = {};

  for (var i=0; i<filter.length; i++) {
    newObj[filter[i]] = obj[filter[i]];
  }
  return newObj;
}


//Usage: 
obj = filterObject(obj, filter);

您無需創建新對象就可以做的另一件事是刪除屬性

var obj = {First: ["One", "Two", "Three"], Second: ["One", "Two", "Three"], Third: ["One", "Two", "Three"]};
var filter = ["Second", "Third"];


function filterProps(obj, filter) {
  for (prop in obj) {
      if (filter.indexOf(prop) == -1) {
          delete obj[prop];
      } 
  };
  return obj;
};

//Usage: 
obj = filterObject(obj, filter);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM