如何使用数组和map函数构建一个javascript对象? [英] how to build a javascript object using an array and the map function?

查看:94
本文介绍了如何使用数组和map函数构建一个javascript对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个频道数组我希望转换为单个对象(channelSettings),每个频道都有一个true / false 属性即可。

I've got an array of channels that I want to transform into a single object (channelSettings) with a true / false property for each channel.

我使用下面的代码工作了,但看起来很冗长。没有temp变量,有没有办法做到这一点?如果我能够驾驭它,那么我也可以驾驭自动执行功能。

I've got it working using the below code but it seems verbose. Is there are way to do it without the "temp" var? If I can get ride of that, then I could get ride of the self executing function as well.

var channels = ["TV", "Billboard", "Spot TV"];


var channelSettings = function() {
    var temp = {};

    channels.map(function(itm, i, a) {
        var channel = itm.toLowerCase().replace(" ", "");
        temp[channel] = false;
    });

    return temp;
}();

我想我试图让map函数返回一个带有属性而不是数组的对象。这可能吗?这是误导吗?建议?

I guess I'm trying to get the map function to return an object with properties instead of an array. Is this possible? Is it mis-guided? Suggestions?

这是我希望它最终看起来的样子:

This is what I'm hoping it looks like in the end:

var channels = ["TV", "Billboard", "Spot TV"];

var channelSettings = channels.map(function(itm, i, a) {
        var channel = itm.toLowerCase().replace(" ", "");
        return ????;
});


推荐答案

使用 .reduce( )函数代替。

var channelSettings = channels.reduce(function(obj, itm) {
        var channel = itm.toLowerCase().replace(" ", "");
        obj[channel] = false;

        return obj;
}, {});

DEMO: http://jsfiddle.net/MjW9T/

第一个参数引用先前返回的项目,第一次迭代除外,它引用数组中的第一个项目或者我们作为空对象提供的种子项目。

The first parameter references the previously returned item, except for the first iteration, where it references either the first item in the Array, or the seeded item, which we provided as an empty object.

第二个参数引用Array中的当前值。只要我们总是返回 obj ,第一个参数将始终是该对象,最终返回值也是如此。

The second parameter references the current value in the Array. As long as we always return obj, the first parameter will always be that object, as will the final return value.

这篇关于如何使用数组和map函数构建一个javascript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆