[英]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,但稍后我们将移植到客户端应用程序,它也适用)。
一种简单的方法是在 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;
}
您可以使用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()
两次。 第一个创建一个外部对象,内部减少创建第一个对象内的每个对象。
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
键的对象,将一个titles
数组作为它的值。
它看起来很干净而且很容易阅读,尤其是当一个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);
return users.reduce((results, u)=> (results[u.id] = u, results), {})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.