在Javascript中对JSON进行分组和排序,同时保持原始密钥

时间:2017-07-11 16:12:22

标签: javascript jquery json underscore.js

我正在寻找一种转换这种JSON的方法:

{  
   "component-0":{  
  "parent":"grid-item-0",
  "position":1
   },
   "component-1":{  
  "parent":"grid-item-0",
  "position":0
   },
   "component-2":{  
  "parent":"grid-item-1",
  "position":0
   } ...
}

到此(按“父”分组并按“位置”排序):

{  
   "grid-item-0":[  
      {  
         "id":"component-1",
         "parent":"grid-item-1",
         "position":0
      },
      {  
         "id":"component-0",
         "parent":"grid-item-0",
         "position":1
      }
   ],
   "grid-item-1":[  
      {  
         "id":"component-2",
         "parent":"grid-item-1",
         "position":0
      }
   ] ...
}

请注意,在分组后保留原始密钥/标识符(“component-0”等)非常重要。我尝试了下划线groupBy方法,但它用一个数字替换了我的id。

提前致谢!

2 个答案:

答案 0 :(得分:3)

<div class="entry-content" itemprop="description">
  <a class="button color-simple" href="http://techaccessok.org/person/std-speaker-2/" rel="bookmark">Nice to meet you!</a>
</div>
var obj = {  
   "component-0":{  
  "parent":"grid-item-0",
  "position":1
   },
   "component-1":{  
  "parent":"grid-item-0",
  "position":0
   },
   "component-2":{  
  "parent":"grid-item-1",
  "position":0
   }
}

_.each(obj, (v, k) => v.id = k)
var grouped = _.groupBy(obj, 'parent');
var sorted = _.mapObject(grouped, v => _.sortBy(v,'position'))
console.log(sorted)

答案 1 :(得分:0)

一个vanilla JS解决方案:

首先我们需要将原始对象转换为对象数组,并为每个对象添加id

var objects = Object.keys(original_object).
  reduce(function(arr, key) {
    arr.push(
      Object.assign({}, original_object[key], { id: key })
    );
    return arr;
  }, []);

这将为我们提供一个具有以下结构的数组:

enter image description here

然后我们按位置排序objects

var sorted_objects = objects.sort(function(a, b) {
  return a.position >= b.position ? 1 : -1;
});

最后,我们按parent

对对象进行分组
var groups = sorted_objects.reduce(function(res, item) {
  res[item.parent] = res[item.parent] || [];
  res[item.parent].push(item);
  return res;
}, {});

最终结果:

enter image description here

最终代码:

var original_object = {  
  "component-0":{  
    "parent":"grid-item-0",
    "position":1
  },
  "component-1":{  
    "parent":"grid-item-0",
    "position":0
  },
  "component-2":{  
    "parent":"grid-item-1",
    "position":0
  }
}

var objects = Object.keys(original_object).
  reduce(function(arr, key) {
    arr.push(
      Object.assign({}, original_object[key], { id: key })
    );
    return arr;
  }, []);

var sorted_objects = objects.sort(function(a, b) {
  return a.position >= b.position ? 1 : -1;
});

var groups = sorted_objects.reduce(function(res, item) {
  res[item.parent] = res[item.parent] || [];
  res[item.parent].push(item);
  return res;
}, {});

console.log(groups);