简体   繁体   中英

transform array using underscore.js

I have an array looking like this:

[Object { id=50, name="My Town"}, Object { id=61, name="My second town"}]

which I need to transform to:

Object { 61=true, 50=true}

How do I do that using underscore.js (or regular js)?

thanks Thomas

You can use just forEach method of native array , in underscore its _.each

 var arr = [{ id:50, name:"My Town"},{ id:61, name:"My second town"}];
 var obj = {};
 arr.forEach(function(val){   obj[val.id] = true; });
 console.log(obj)//Object { 61=true, 50=true}
var res = {}; var objs = [ { id: 50 }, { id: 61} ]; objs.forEach(function (d) { res[d.id] = true; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM