Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #31567
| Path | csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail |
|---|---|
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
| Newsgroups | comp.lang.javascript |
| Subject | Re: Filter array of objects for property |
| Date | Thu, 13 Oct 2016 00:27:03 +0100 |
| Organization | A noiseless patient Spider |
| Lines | 62 |
| Message-ID | <877f9d87y0.fsf@bsb.me.uk> (permalink) |
| References | <IKWdnYrudsxAIWPKnZ2dnUU7-XXNnZ2d@westnet.com.au> |
| Mime-Version | 1.0 |
| Content-Type | text/plain |
| Injection-Info | mx02.eternal-september.org; posting-host="d55b9a4918507de28ffdc8b5228c4096"; logging-data="2154"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18cUiuJqP6zKgLp4IprDzdHryVlIEpqAJg=" |
| Cancel-Lock | sha1:D6ZB5PaKSSsPXpkroe9bkLbohXQ= sha1:fd+uU0gBCtpKpnY4+v2QMDxiepU= |
| X-BSB-Auth | 1.184af6a00ee750472854.20161013002703BST.877f9d87y0.fsf@bsb.me.uk |
| Xref | csiph.com comp.lang.javascript:31567 |
Show key headers only | View raw
Andrew Poulos <ap_prog@hotmail.com> writes:
> If I have an array that looks like this
>
> var arr =
> [
> {
> a: "foo_2",
> b: "trigger_1",
> c: "bar_3"
> },
> {
> a: "foo_3",
> b: "foo_4",
> c: "bar_4"
> },
> {
> a: "foo_6",
> b: "trigger_5",
> c: "bar_5"
> }
> ...
> ];
>
> and to get an array of all "b" values that start with "trigger_" and
> end with a number I'm calling
>
> function getValues(theArr, pre) {
> var i = 0,
> fnd = [],
> tmp;
>
> for (i = 0; i < theArr.length; i++) {
> tmp = theArr[i].b;
> if ( /trigger_\d+$/.test(tmp) ) {
> fnd.push(tmp);
> }
> }
>
> return fnd;
> }
>
> While this works I'd like the argument "pre" to be a string I pass to
> the regexp so that I can test other values and not just "trigger_" but
> I don't know how.
You can construct a RegExp from a string:
RegExp(pre + '\\d+$').test(tmp)
> And secondly is there an easier way to get values for an array of
> objects?
One way would be to use map and filter. Combining these with the arrow
notation for functions you could write:
arr.map(x => x.b).filter(x => RegExp(pre + '\\d+$').test(x))
(ES6 would also permit you to write `${pre}\\d+$`)
--
Ben.
Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Filter array of objects for property Andrew Poulos <ap_prog@hotmail.com> - 2016-10-13 09:44 +1100
Re: Filter array of objects for property Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-10-13 00:27 +0100
Re: Filter array of objects for property Andrew Poulos <ap_prog@hotmail.com> - 2016-10-13 12:57 +1100
Re: Filter array of objects for property Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-10-13 11:21 +0100
Re: Filter array of objects for property Bunny Bocarisse <ben.usenet@bsb.me.uk> - 2016-10-13 13:28 +0100
csiph-web