如何将模型对象数组转换为以模型 ID 作为键的对象?

How to convert array of model objects to object with model ids as keys?

在 Javascript 中,我有一个模型对象数组:

[  
   {  
      "id":13,
      "title":"Some title 1",
      "time": "friday"
      ...
   },
   {  
      "id":15,
      "title":"Some title 3",
      "time": "Saturday"
      ...
   },
   {  
      "id":16,
      ...
   },
   ...
]

(每个对象上有超过 2 个值和属性) 我想得到一个对象,每个 id 从数组移动到键,像这样:

{
  13: {
    title: "Some title 1",
    time: "Friday"
    ...
  },
  15: {
    title: "Some title 3",
    time: "Saturday"
    ...
  },
  16: {
    ...
  },
  ...
}

我正在使用 Rails 视图 .to_json include: {} 语法生成数组,因此 rails 中的答案也适用于我。我将使用带有 Redux 的结果对象作为初始状态,因此某种 Redux 答案也很棒。也对 es6 和 es5 答案感兴趣(我将使用 es5 答案,因为 Rails 不会在视图中编译 es6,但稍后我们将移植到它也适用的客户端应用程序)。

您可以使用 reduce() 创建对象,在内部您可以使用 Object.keys()forEach() 循环来创建内部对象。

var data = [{
  "id": 13,
  "title": "Some title 1",
  'lorem': 'ipsum'
}, {
  "id": 15,
  "title": "Some title 3",
}, {
  "id": 16,
}]

var result = data.reduce(function(r, e) {
  r[e.id] = {}
  Object.keys(e).forEach(function(k) {
    if(k != 'id') r[e.id] = Object.assign(r[e.id], {[k]: e[k]})
  })
  return r
}, {})

console.log(result)

另一种方法是使用reduce()两次。第一个创建一个外部对象,内部 reduce 在第一个对象中创建每个对象。

var data = [{"id":13,"title":"Some title 1","lorem":"ipsum"},{"id":15,"title":"Some title 3"},{"id":16}]

var result = data.reduce(function(r, e) {
  r[e.id] = Object.keys(e).reduce(function(o, a) {
   if(a != 'id') o[a] = e[a]
    return o;
  }, {})
  return r;
}, {})

console.log(result)

使用下面的代码

try {
            JSONArray jsonArray=new JSONArray("yourJsonString");
            for(int i=0;i<jsonArray.length();i++){


                JSONObject outer_jsonObject=new JSONObject();
                JSONObject inner_jsonObject=new JSONObject();

                inner_jsonObject.put("title",jsonArray.getJSONObject(i).getString("title"));
                outer_jsonObject.put(jsonArray.getJSONObject(i).getString("id"),inner_jsonObject);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

我建议您采用以下方法。

对于每个 id,分配一个带有 titles 键的 object,保存一个标题数组作为它的值。

它看起来很干净而且易于阅读,尤其是当标题很少时 id

var arr=[{id:13,title:"Some title 1"},{id:15,title1:"Some title 3",title2:"Some title 4"},{id:16}],     result = [];

arr.forEach(function(v){
  var obj = {};
  var titles = {};
  var titlesArr = [];
  Object.keys(v).forEach(function(c){
    if (c != 'id') {
      titlesArr.push(v[c]);
      titles.titles = titlesArr;
    }
  });
  obj.id = titles;
  result.push(obj);
});

console.log(result);

一个简单的方法是遍历 Ruby:

中的数组
foo = [  
   {  
      "id":13,
      "title":"Some title 1",
      ...
   },
   {  
      "id":15,
      "title":"Some title 3",
      ...
   }]

result = {}
foo.each {|f| result[f.delete('id')] = f}

最简单的解决方案是遍历数组并将每个项目的副本附加到新对象:

let result = {};
for (let item of data) {
  let newObject = Object.assign({}, item);
  result[newObject.id] = newObject;
  delete newObject.id;
}

如果以后不需要数据数组,它会变得更简单:

let result = {};
for (let item of data) {
  result[item.id] = item;
  delete item.id;
}
return users.reduce((results, u)=> (results[u.id] = u, results), {})