TypeScript-根据属性值将对象移出数组 [英] TypeScript - Take object out of array based on attribute value

查看:271
本文介绍了TypeScript-根据属性值将对象移出数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组如下:

array = [object {id: 1, value: "itemname"}, object {id: 2, value: "itemname"}, ...]

我所有的对象都具有相同的着装,但具有不同的值.

all my objects have the same attibutes, but with different values.

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

Is there an easy way I can use a WHERE statement for that array?

将对象带到其中object.id = var

Take the object where object.id = var

还是只需要遍历整个数组并检查每个项目?我的数组有100多个条目,所以我想知道是否有更有效的方法

or do I just need to loop over the entire array and check every item? My array has over a 100 entries, so I wanted to know if there was a more efficient way

推荐答案

使用Array.find:

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

let item1 = array.find(i => i.id === 1);

在MDN上

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

这篇关于TypeScript-根据属性值将对象移出数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆