从数组的图像对象创建对象的图像类别数组

时间:2016-08-02 12:43:25

标签: javascript arrays angularjs

我有以下数组Object

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

我想跟随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'] }
 ]

这是小提琴 http://jsfiddle.net/ojehojf8/

2 个答案:

答案 0 :(得分:0)

是否需要有阵列?

只使用此处How to create a hash or dictionary object in JavaScript

中提到的对象

应该类似于以下

struct settings
{
    std::string config_value;
}

答案 1 :(得分:0)

你不需要Angular:

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)

只是为了好玩,相同功能的一行实现:

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)