JavaScript中具有根和嵌套级别属性的过滤器

tez616oj  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(124)

输入:

// First Array
const input1 = [{
    'name': "name1",
    'email': "emai2@email.com",
    'age': 10,
    'address': {
      'city': "city1"
    }
  },
  {
    'name': "name2",
    'email': "emai2@email.com",
    'age': 20,
    'address': {
      'city': "city2"
    }
  }
];

// Second Array
const input2 = [{
    'id': 1,
    'fullname': "name1",
    'emailaddress': "emai2@email.com",
    'age': 10,
    'address': {
      'city': "city1"
    }
  },
  {
    'id': 5,
    'name': "name2",
    'email': "emai55@email.com",
    'age': 20,
    'address': {
      'city': "city3"
    }
  }
];

const filter = [{
  "filter1Key": "name",
  "filter2Key": "address.city"
}];

const matchArray = [];
const newArray = [];
let filterInput = '';

const test1 = input1.filter((data) => input2.some((obj) => filter.every(key => data[key.filter1Key] === obj[key.filter2Key])));
console.log(test1);

这里我想过滤记录根级关键字以及与嵌套级关键字。在这种情况下,根级关键字是名称和嵌套级关键字是城市,这是内部地址,如果两者将匹配这些记录应该过滤

jdgnovmf

jdgnovmf1#

您可以使用Lodash intersectionBy函数获取2个数组之间的匹配项。
至于匹配条件,您还可以使用Lodash get函数,该函数理解点符号以访问嵌套属性。

// First Array
const input1 = [{
    'name': "name1",
    'email': "emai2@email.com",
    'age': 10,
    'address': {
      'city': "city1"
    }
  },
  {
    'name': "name2",
    'email': "emai2@email.com",
    'age': 20,
    'address': {
      'city': "city2"
    }
  }
];

// Second Array
const input2 = [{
    'id': 1,
    // 'fullname': "name1", // Typo?
    'name': "name1",
    'emailaddress': "emai2@email.com",
    'age': 10,
    'address': {
      'city': "city1"
    }
  },
  {
    'id': 5,
    'name': "name2",
    'email': "emai55@email.com",
    'age': 20,
    'address': {
      'city': "city3"
    }
  }
];

// You can directly specify all AND keyPaths
// in the filter array
const filter = [
  "name",
  "address.city"
];

const test1 = _.intersectionBy(
  input1,
  input2,
  (item) => JSON.stringify(filter.map(
    (keyPath) => _.get(item, keyPath)
  ))
);

console.log(test1); // Result: 1st item of input1 (matching name and address.city of 1st item of input2)
<script src="
https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js
"></script>

注:我假设input2第一项中有一个排印错误('fullname'键应为'name',以与其他项保持一致)。

相关问题