admin管理员组

文章数量:1356946

I am populating an array of objects in knockoutjs

I wanted to avoid the use of foreach, so I tried to data-bind the first item

if i use the below code it is working fine

<div class="loader" data-bind="foreach: Items" >
        <span data-bind="text: name"></span>
    </div>

But if i use, the one below, its not working

<div class="loader">
        <span data-bind="text: Items[0].name"></span>
    </div>

What is the mistake in the second way?

The error I am getting is

Uncaught TypeError: Unable to process binding "text: function (){return Items[0].name }" Message: Cannot read property 'name' of undefined

I am populating an array of objects in knockoutjs

I wanted to avoid the use of foreach, so I tried to data-bind the first item

if i use the below code it is working fine

<div class="loader" data-bind="foreach: Items" >
        <span data-bind="text: name"></span>
    </div>

But if i use, the one below, its not working

<div class="loader">
        <span data-bind="text: Items[0].name"></span>
    </div>

What is the mistake in the second way?

The error I am getting is

Uncaught TypeError: Unable to process binding "text: function (){return Items[0].name }" Message: Cannot read property 'name' of undefined

Share Improve this question asked Dec 8, 2015 at 9:39 Vignesh SubramanianVignesh Subramanian 7,30914 gold badges96 silver badges158 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

well you need to unwrap the observableArray Items to read it's content using () notation .

Try like this

<div class="loader">
     <span data-bind="text: Items()[0].name"></span>
</div>
text: Items()[0].name

Check it.

Use either Items()[0].name or ko.unwrap(Items)[0] I would remend the second one since it is safer because it would return the array even if Items is not an observable array, hence helps avoiding exceptions.

本文标签: javascriptgetting first element of array in knockout jsStack Overflow