I have below list in javascript
–
[
{
"id" : 111,
"type": "BASE",
"someOtherProp": "other",
"linkedId": 222
},
{
"id" : 222,
"type": "CHILD",
"someOtherProp": "other",
"linkedId": 111
},
{
"id" : 333,
"type": "SOMEOTHERTYPE",
"someOtherProp": "other",
"linkedId": 444
}
]
I want to check in list if type === 'BASE'
, get the linkedId
of matching type and check in same list if CHILD
is present. If CHILD
is not present then break the loop
and throw the exception or alert the message.
Note : BASE’s object linkedId
is CHILD’s object id
.
I am planning to use nested loop but looking a better approach if any for this.
Thank you.
2
Answers
You can avoid nested loops by using a
Map
to store references to the objects by theirid
, making it easier and faster to look up related objects. Here’s an approach usingreduce
andMap
:Efficient way to handle the problem:
reduce
to create aMap
withid
as the key and the object as the value. This allows you to look up items by theirid
in constant time.forEach
to iterate through the list, and for eachBASE
object, look up itslinkedId
in theMap
.linkedId
exists and itstype
isCHILD
, the check passes. Otherwise, an error is thrown.This avoids nested loops and performs lookups efficiently using the
Map
.if you just want to show alert/exception for the type
BASE
withoutCHILD
you can do anything with the array
baseWithoutChild