在Javascript中,我有一组模型对象:
[
{
"id":13,
"title":"Some title 1",
"time": "friday"
...
},
{
"id":15,
"title":"Some title 3",
"time": "Saturday"
...
},
{
"id":16,
...
},
...
]
(每个对象上有两个以上的值和属性)我想从数组中获取每个id都移到键的对象,就像这样:
{
13: {
title: "Some title 1",
time: "Friday"
...
},
15: {
title: "Some title 3",
time: "Saturday"
...
},
16: {
...
},
...
}
我正在使用Rails view .to_json include: {}
语法生成数组,因此用rails回答也对我有用。我将结果对象与Redux一起用于初始状态,因此某种Redux答案也很棒。同时也会对es6和es5答案都感兴趣(尽管我将使用es5答案,因为Rails不会在视图中编译es6,但稍后我们将移植到也将适用的客户端应用程序。)
最简单的解决方案是遍历数组并将每个项目的副本附加到新对象:
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;
}
一种简单的方法是仅在Ruby中遍历数组:
foo = [
{
"id":13,
"title":"Some title 1",
...
},
{
"id":15,
"title":"Some title 3",
...
}]
result = {}
foo.each {|f| result[f.delete('id')] = f}
您可以使用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
键分配一个对象,并保留标题数组作为其值。
它看起来很干净而且易于阅读,特别是当一个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), {})