使用underscore.js转换数组

transform array using underscore.js

本文关键字:数组 转换 js underscore 使用      更新时间:2023-09-26

我有一个数组,如下所示:

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

我需要转换为:

Object { 61=true, 50=true}

如何使用underscore.js(或常规js)实现这一点?

谢谢Thomas

您可以只使用本机数组的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; });