简体   繁体   English

使用underscore.js变换数组

[英]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)? 我如何使用underscore.js(或常规js)?

thanks Thomas 谢谢托马斯

You can use just forEach method of native array , in underscore its _.each 您可以使用原生数组的forEach方法,在其_.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; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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