0

I have following array of Object

$scope.images = [
      {key: 'shop1/images/a1.jpg'},
      {key: 'shop2/images/a2.jpg'},
      {key: 'shop1/images/a3.jpg'},
      {key: 'shop3/images/a4.jpg'}    
    ]

I want to following array of object from above json

[
      { 'key':'shop1', 'images':['shop1/images/a1.jpg', 'shop1/images/a3.jpg'] }
      { 'key':'shop2', 'images':['shop2/images/a2.jpg'] }
      { 'key':'shop3', 'images':['shop3/images/a4.jpg'] }
 ]

Here is fiddle http://jsfiddle.net/ojehojf8/

Mehul Mali
  • 3,084
  • 4
  • 14
  • 28

2 Answers2

0

Is it necessary to have an array?

just use a object like mentioned in here How to create a hash or dictionary object in JavaScript

should be something like the following

angular.forEach($scope.images, function(obj){
    $scope.imgsObj = {};
    var res = obj.key.split("/");
    if($scope.imgsObj[res[0]]){
      $scope.imgsObj[res[0]].push(obj);
    }else{
      $scope.imgsObj[res[0]] = [obj];
    }
}
Community
  • 1
  • 1
Thomas Zoé
  • 423
  • 3
  • 16
0

You do not need Angular for this:

var images = [
      {key: 'shop1/images/a1.jpg'},
      {key: 'shop2/images/a2.jpg'},
      {key: 'shop1/images/a3.jpg'},
      {key: 'shop3/images/a4.jpg'},
      {key: 'shop1/images/a5.jpg'},
      {key: 'shop2/images/a6.jpg'},
      {key: 'shop1/images/a7.jpg'},
      {key: 'shop1/images/a8.jpg'},
      {key: 'shop3/images/a9.jpg'},
      {key: 'shop2/images/a10.jpg'}      
]

// First of all, we collect the data by key
var result = {};
for (let i = 0; i < images.length; i++) {
  let key = images[i].key.split('/')[0];
  if (!result[key]) {result[key] = [];}
  result[key].push(images[i].key);
}

// Now we transform them in the result you want
var arr = [];
for (let i in result) {
  if (!result.hasOwnProperty(i)) continue;
  arr.push({key: i, images: result[i]});
}

console.log(arr)

Just for fun, a one line implementation of the same function:

var images = [
      {key: 'shop1/images/a1.jpg'},
      {key: 'shop2/images/a2.jpg'},
      {key: 'shop1/images/a3.jpg'},
      {key: 'shop3/images/a4.jpg'},
      {key: 'shop1/images/a5.jpg'},
      {key: 'shop2/images/a6.jpg'},
      {key: 'shop1/images/a7.jpg'},
      {key: 'shop1/images/a8.jpg'},
      {key: 'shop3/images/a9.jpg'},
      {key: 'shop2/images/a10.jpg'}      
]



var result = images.map(img => img.key.split('/')[0]).filter((v, i, a) => a.indexOf(v) === i).map(k => {return {key: k, images: images.filter(img => img.key.split('/')[0] === k).map(img => img.key)}});
console.log(result)
rpadovani
  • 7,101
  • 2
  • 31
  • 50