Samantha J Samantha J - 6 months ago 7
Javascript Question

How can I return a property value for the first element in an array or 0 if there are no elements?

In my HTML I have this code block:

<div ng-click="wos.wordWordFormRowClicked(wf)"
ng-repeat="wf in word.wordForms">
...
</div>


The
word
object can have 0 or many
wordForms
and each
wordForm
has a property
wordFormIdentityId
.

In javascript how can I get the
wordFormIdentityId
of the first
wordForm
or return 0 if there are no wordForms. Hope this makes sense, if not please ask and I will try to explain more.

Here are the typescript interfaces:

interface IWord {
wordForms: IWordForm[];
wordId: string;
}

interface IWordForm {
definition: string;
wordFormId: string;
wordFormIdentity: number;
wordId: string;
}

Answer

Am I missing something or does this handle it? I responded in Typescript as well.

function getFirstId (word:IWord) :number {
    if(word && word.wordForms && word.wordForms.length > 0) {
        return word.wordForms[0].wordFormIdentity;
    }
    return 0;
}
Comments