使用ES6 / lodash进行迭代和过滤

时间:2018-04-17 06:49:51

标签: javascript ecmascript-6 lodash

我们有一系列对象,如:

const persons = [{
    name: "john",
    age: 23
}, {
    name: "lisa",
    age: 43
}, {
    name: "jim",
    age: 101
}, {
    name: "bob",
    age: 67
}];

对象

中对象的属性值数组
const names = ["lisa", "bob"]

我们如何使用es6在names数组中找到名字的人,比如:

const filteredPersons = [{
    name: "lisa",
    age: 43
}, {
    name: "bob",
    age: 67
}];

6 个答案:

答案 0 :(得分:4)

ES6

filter函数与谓词一起使用,并在其中检查names数组中是否存在名称。

const persons = [
    {name: "john", age:23},
    {name: "lisa", age:43},
    {name: "jim", age:101},
    {name: "bob", age:67}
];

const names = ["lisa", "bob"];

const filtered = persons.filter(person => names.includes(person.name));

console.log(filtered);

答案 1 :(得分:3)

您可以使用filter()inlcudes()来获取所需的结果。

<强>样本

&#13;
&#13;
const persons = [{
  name: "john",
  age: 23
}, {
  name: "lisa",
  age: 43
}, {
  name: "jim",
  age: 101
}, {
  name: "bob",
  age: 67
}];
const names = ["lisa", "bob"];

console.log(persons.filter(({
  name
}) => names.includes(name)))
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 2 :(得分:3)

我建议使用indexOf,因为includes在IE浏览器中不起作用。此外,使用{name}作为解构赋值,它将保存对象的name属性值。

&#13;
&#13;
const persons = [{
  name: "john",
  age: 23
}, {
  name: "lisa",
  age: 43
}, {
  name: "jim",
  age: 101
}, {
  name: "bob",
  age: 67
}];
const names = ["lisa", "bob"];

console.log(persons.filter(({name}) => names.indexOf(name) !== -1))
&#13;
&#13;
&#13;

答案 3 :(得分:1)

lodash

您可以尝试以下

const persons = [{name: "john", age: 23},
    {name: "lisa",age: 43}, 
    {name: "jim", age: 101}, 
    {name: "bob",age: 67}];


const names = ["lisa", "bob"]


const filteredPersons = _.filter(persons, function(person) {
    return _.indexOf(names, person.name) !== -1;
});

console.log(filteredPersons);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

答案 4 :(得分:1)

如果您想以n复杂度执行此操作,可以使用以下方法:

  1. 使用关键字创建一个地图作为人物的名称和值作为人物的对象。
  2. 映射条件数组并从步骤1中创建的地图中提取人物对象。
  3. 这是一个有效的演示:

    &#13;
    &#13;
    const persons = [{
      name: "john",
      age: 23
    }, {
      name: "lisa",
      age: 43
    }, {
      name: "jim",
      age: 101
    }, {
      name: "bob",
      age: 67
    }];
    
    const names = ["lisa", "bob"];
    const map = persons.reduce((acc, item) => {
      acc[item.name] = item;
      return acc;
    }, {});
    const result = names.map(name => map[name]);
    console.log(result);
    &#13;
    &#13;
    &#13;

    注意:此解决方案假定源数组中只有唯一的人名。需要调整它来处理重复项。

答案 5 :(得分:1)

有关详细信息,请参阅ClosuresSetArray.prototype.filter()

// Input.
const persons = [{name: "john",age: 23}, {name: "lisa",age: 43}, {name: "jim",age: 101}, {name: "bob",age: 67}]
const names = ["lisa", "bob"]

// Filter.
const filter = (A, B) => (s => A.filter(x => s.has(x.name)))(new Set(B))

// Output.
const output = filter(persons, names)

// Proof.
console.log(output)