JSON:
{resources:
[
{type:sound, content:0},
{type:movie, content:1},
{type:image, content:2},
...
]}
How do i most effeciently get the content of objects with type=image? can i avoid having to loop through the objects?
Coming from a background working with xml i am used to working with queries inside the getter.
The above sample in xml would let me get the content of the image object by simply writing resources.object(type == "image").content
<resources>
<object type="sound">
<content>0</content>
</object>
<object type="movie">
<content>1</content>
</object>
<object type="image">
<content>2</content>
</object>
...
</resources>
You can use lodash for this.
In your case the solution would look like this -
_.filter(resources, { 'type': 'image' });
In vanilla javascript you can use filter
to filter them and map
to get an array of the contents:
let json = {resources:
[
{type:"sound", content:0},
{type:"movie", content:1},
{type:"image", content:2}
]};
json.resources.filter( r => r.type === "image" ).map( r => r.content)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.