TypeScript - 根据属性值将对象从数组中取出

Nic*_*las 36 javascript arrays typescript

我的数组看起来像这样:

array = [object {id: 1, value: "itemname"}, object {id: 2, value: "itemname"}, ...]
Run Code Online (Sandbox Code Playgroud)

我的所有对象都具有相同的属性,但具有不同的值.

有没有一种简单的方法可以为该数组使用WHERE语句?

获取object.id = var的对象

或者我只需要遍历整个阵列并检查每个项目?我的阵列有超过100个条目,所以我想知道是否有更有效的方法

Sar*_*ana 87

用途Array.find:

let array = [
    { id: 1, value: "itemname" },
    { id: 2, value: "itemname" }
];

let item1 = array.find(i => i.id === 1);
Run Code Online (Sandbox Code Playgroud)

MDN上的Array.find:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

  • 谢谢,这个解决方案是最干净的,它的工作原理! (4认同)

Nit*_*mer 5

我会使用filterreduce

let array = [
    { id: 1, value: "itemname" },
    { id: 2, value: "itemname" }
];

let item1 = array.filter(item => item.id === 1)[0];
let item2 = array.reduce((prev, current) => prev || current.id === 1 ? current : null);

console.log(item1); // Object {id: 1, value: "itemname"}
console.log(item2); // Object {id: 1, value: "itemname"}
Run Code Online (Sandbox Code Playgroud)

操场上的代码

如果您在整个阵列上关心迭代,然后使用一些

let item;
array.some(i => {
    if (i.id === 1) {
        item = i;
        return true;
    }
    return false;
});
Run Code Online (Sandbox Code Playgroud)

操场上的代码

  • Array有一个find()方法,该方法返回第一次出现的https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/find (4认同)

Aam*_*mir 5

如果您需要在不指定列的情况下从对象的所有字段中搜索值,您可以使用 TypeScript 动态搜索对象数组中的某个值

 var searchText = 'first';

let items = [
            { id: 1, name: "first", grade: "A" },
            { id: 2, name: "second", grade: "B" }
        ];

This below code will search for the value

var result = items.filter(item => 
             Object.keys(item).some(k => item[k] != null && 
             item[k].toString().toLowerCase()
             .includes(searchText.toLowerCase()))
             );
Run Code Online (Sandbox Code Playgroud)

可以使用相同的方法使用 TypeScript 在 angularjs 4 中制作搜索过滤器管道