Magento – Knockout js : Read parent of parent’s data

knockoutknockoutjsmagento2

I want to read the parent of parent elements data. But, I can't able to read it properly.

My Array Screenshot :

enter image description here

My Code :

<!-- ko foreach: { data: Object.keys($parent.optionParam()[main_id]), as: 'attribute' } -->
    <div class="product-custom-option-select">
        <p style="font-weight:bold;color:blue" data-bind="text:attribute"></p>
        <!-- ko if: Array.isArray(Object.keys($parent.optionParam()[main_id][attribute])) -->
            <p style="font-weight:bold;color:green" data-bind="text:attribute"></p>
            <!-- ko foreach: $parents[1].optionParam[$parentContext.$index()][attribute] -->
                <p class="options-label" data-bind="text:sub_id"></p>
            <!-- /ko -->
        <!-- /ko -->
        <!-- ko if: !Array.isArray($parent.optionParam()[$index][attribute]) -->
            <p style="font-weight:bold;color:red" data-bind="text:attribute"></p>
            <p class="options-label" data-bind="text:attribute[$parents[1].main_id]"></p>
        <!-- /ko -->
    </div>
<!-- /ko -->

Using $parent.optionParam()[main_id] I can able to access 0 element array. So, in first <p> tag I get Size text as attribute.

Now, I want to read there are sub-element available in Size or Color, If true then, First Array.isArray() should be true and I can able to read sub_color or sub_id field value.

<!-- ko if: Array.isArray(Object.keys($parent.optionParam()[main_id][attribute])) -->

This line always returns an error to me.

How can I read it?

Any help would be appreciated.

Best Answer

$parent is essentially an array with all the parents in the current context.

So $parent or $parent[0] refers to immediate parent, $parent[1] will refer to grandparent or parent of parent and so on.

Related Topic