通过在json对象的每个属性中找到的索引来排序json对象的最佳方法是什么?

What would be the best way to order a json object by an index found within each of it's properties?

本文关键字:对象 json 排序 索引 最佳 是什么 方法 属性      更新时间:2023-09-26

我有一个像这样的对象数组

obj = [
    {
      id: 3,
      data: foo
    },
    {
      id: 7,
      data: bar
    }
]

但是我需要把它放到

 obj = {
    3: {
        id: 3,
        data: foo
    },
    7: {
        data: bar
    }
 }
不需要在子对象中包含

的id,但可能会很方便。实现这一目标的最佳方式是什么?我不确定是否有一种简单的方法来提取属性作为索引?

谢谢你的帮助!

obj2 = {};
obj.forEach(function(x){
    obj2[x.id] = x;
});

在处理对象操作时,应该考虑使用Underscore JavaScript库。它确实使使用它们更容易,并将为您处理浏览器的不兼容性。特别是在这里,我将使用map函数:

var newObj = _.map(obj, function (subobj) {
  var tempObj = {};
  tempObj[subobj.id] = subobj;
  return tempObj;
});