Sampath
Sampath

Reputation: 90

Merging duplicate objects with same id into single object from json data using angular js

i get a json data from api call for errors list of various items with id, name, error_type and message. I need to display a header with name and id of the item and under that a list of all errors belonging to that id. i am using unique filter in angular but that is skipping the next object with same id. I want some help to merge the object property when the id is same.

var items =[ {    
    "id": 83739,
    "name": "abcd",
    "type": "error",
    "msg": "For Macros, x >= y"
},
{
    "id": 83739,
    "name": "abcd",
    "type": "warning",
    "msg": "Missing Power Condition"
},{
    "id": 83740,
    "name": "efgh",
    "type": "error",
    "msg": "Missing Power supply"
}]
<div ng-repeat="item in items | unique:'id'">
 <h4><a href="#/product/item/{{item.id}}">  {{io.item}}</a></h4>
 <ul>
   <li > {{item.type}}: {{item.msg}}</li>
 </ul>
</div>

My output i need is like this

<div>
  <h4><a href="#/product/item/83739"> abcd</a></h4>
  <ul>
    <li > error: For Macros, x >= y</li>
    <li > warning: Missing Power Condition</li>
   
  </ul>
</div>

<div>
  <h4><a href="#/product/item/83740}"> efgh</a></h4>
  <ul>
     <li > error: Missing Power supply</li>
  </ul>
</div>

Upvotes: 1

Views: 300

Answers (1)

jbrown
jbrown

Reputation: 3025

Add a ng-repeat directive to your li and apply a filter, like this:

<li ng-repeat="i in items | filter: {id: item.id}"> {{i.type}}: {{i.msg}}</li>

In context:

<div ng-repeat="item in items | unique:'id'">
   <h4>
      <a href="#/product/item/{{item.id}}">  {{io.item}}</a>
   </h4>
   <ul>
      <li ng-repeat="i in items | filter: {id: item.id}"> {{i.type}}: {{i.msg}}</li>
   </ul>
</div>

Here's a working plunk

Upvotes: 1

Related Questions