javascript - How to convert array of model objects to object with model ids as keys? - Stack Overflow

In Javascript I have an array of model objects:[{"id":13,"title":"Some tit

In Javascript I have an array of model objects:

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

(there is more than 2 values and properties on each object) I want to get an object with each id from the array moved to key, like so:

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

I am producing the array with Rails view .to_json include: {} syntax, so an answer in rails would also work for me. I will use the result object with Redux for an initial state so some kind of Redux answer is great too. Also would be interested in both es6 and es5 answer (I will use es5 answer though because Rails doesn't pile es6 in views, but later we are porting to client side application where it would also apply).

In Javascript I have an array of model objects:

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

(there is more than 2 values and properties on each object) I want to get an object with each id from the array moved to key, like so:

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

I am producing the array with Rails view .to_json include: {} syntax, so an answer in rails would also work for me. I will use the result object with Redux for an initial state so some kind of Redux answer is great too. Also would be interested in both es6 and es5 answer (I will use es5 answer though because Rails doesn't pile es6 in views, but later we are porting to client side application where it would also apply).

Share Improve this question edited Mar 2, 2017 at 13:22 Aurimas asked Mar 2, 2017 at 11:39 AurimasAurimas 2,7375 gold badges30 silver badges39 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 3

The simplest solution is to iterate over the array and attach a copy of each item to a new object:

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

If you don't need the data array later on it gets even simpler:

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

A simple way would be to just iterate through the array in Ruby:

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

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

You can use reduce() to create object and inside you can loop object properties with Object.keys() and forEach() loop to create inner objects.

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)

Another approach is to use reduce() two times. First one to create one outer object and inner reduce to create each object inside first object.

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)

return users.reduce((results, u)=> (results[u.id] = u, results), {})

Use below code

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();
        }

I would suggest you following approach.

For every id, assign an object with titles key, holding an array of titles as it's value.

It looks clean and it's easily readable, especially when there's few titles for one 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744213116a4563429.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信