bruh
bruh

Reputation: 2305

Angular ng-repeat over complex object

I have an object containing 2 objects.

Each of those objects contain an array with 2 objects:

ctrl.mainArray = {
  outsideObject_1: {
    insideArray = [
      insideObject_1: { value1: 'someValue', value2: 'someOtherValue' },
      insideObject_2: { value1: 'someValue', value2: 'someOtherValue' }
    ]
  },
  outsideObject_2: {
    insideArray = [
      insideObject_1: { value1: 'someValue', value2: 'someOtherValue' },
      insideObject_2: { value1: 'someValue', value2: 'someOtherValue' }
    ]
  };
};

I want to display the values of insideObject_x from my template:

<ul>
  <li ng-repeat="item in ctrl.mainArray track by item.insideArray[$index]>
    <!-- CASE #1 -->
    First value: {{item.insideArray[0].value1}}

    <!-- CASE #2 -->
    First value: {{item.insideArray[$index].value1}}
  </li>
</ul>

In CASE #1 I can print out the FIRST value, from the FIRST OBJECT in each insideArray. I want to print value1 from EACH insideObject_x

In CASE #2 I can print out the FIRST value, from the FIRST OBJECT in ONLY the first insideArray.

What am I doing wrong? I should be printing value1, 4 different times.

Upvotes: 1

Views: 558

Answers (1)

Sean Mishra
Sean Mishra

Reputation: 309

I didn't understand what exactly you want as output, but assuming you want to print the value of the value1 property on each object inside of all insideArrays, I think you should handle the logic on the script side.

HTML

<ul ng-app="myApp" ng-controller="mainController as mainCtrl">
  <li ng-repeat="value in mainCtrl.values track by $index">
    First value: {{value}}
  </li>
</ul>

JavaScript (Angular)

(() => {
angular.module("myApp", [])
    .controller("mainController", function() {
        let ctrl = this;

        ctrl.mainObj = {
            outsideObject_1: {
                insideArray : [
                    { value1: 'someValue', value2: 'someOtherValue' },
                    { value1: 'someValue', value2: 'someOtherValue' }
                ]
            },
            outsideObject_2: {
                insideArray : [
                    { value1: 'someValue', value2: 'someOtherValue' },
                    { value1: 'someValue', value2: 'someOtherValue' }
                ]
            }
        };

        ctrl.values = [];

        for (let obj in ctrl.mainObj) {
            for(let val of ctrl.mainObj[obj].insideArray) {
                ctrl['values'].push(val.value1);
            }
        }
});
})();

CodePen: http://codepen.io/cod3rguy/pen/ggbMKz?editors=1010


If you want all the property values (value1, value2, etc.) on the objects in insideArrays, you can slighty modify the logic that is populating the values array in the above code as such:-

for (let obj in ctrl.mainObj) {
    for(let val of ctrl.mainObj[obj].insideArray) {
        for (let v in val) {
            ctrl['values'].push(val[v]);
        }
    }
}

Upvotes: 2

Related Questions