[英]transform array using underscore.js
我有一個看起來像這樣的數組:
[Object { id=50, name="My Town"}, Object { id=61, name="My second town"}]
我需要轉換為:
Object { 61=true, 50=true}
我如何使用underscore.js(或常規js)?
謝謝托馬斯
您可以使用原生數組的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.