如何使用数组和 map 函数构建一个 javascript 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11006748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:47:38  来源:igfitidea点击:

how to build a javascript object using an array and the map function?

javascript

提问by DanielEli

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

我有一组通道,我想将它们转换为单个对象(channelSettings),每个通道都有一个 true/false属性

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;
}();

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?

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

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 ????;
});

回答by

Use a .reduce()function instead.

改用.reduce()函数。

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

        return obj;
}, {});

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

演示: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.

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

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.

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

回答by Flambino

The mapfunction takes an array, and returns an array. Nothing else. But you can use reduce:

map函数接受一个数组,并返回一个数组。没有其他的。但你可以使用reduce

var settings = ["TV", "Billboard", "Spot TV"].reduce(function(obj, item) {
   obj[item.toLowerCase().replace(" ", "")] = false; // probably too concise
   return obj // yay, we can skip a semi-colon here :-P
}, {});

Well, "am not i am" beat me to it, but anyway:
mapnot only returns arrays, but also only returns arrays of the same length as the original. It's meant for transforming one array's values 1:1 into a new array. reduceis meant to "reduce an array to a single value". Hence its use here.

好吧,“我不是我”打败了我,但无论如何:
map不仅返回数组,而且只返回与原始数组长度相同的数组。它用于将一个数组的值 1:1 转换为一个新数组。reduce旨在“将数组减少为单个值”。因此它在这里使用。

If you use a straight forloop or the forEachmethod to add properties to an object, you do need to declare that object. So, no, you can't do without tempin your code (unless you use reduceinstead of a loop).

如果使用直接for循环或forEach方法向对象添加属性,则需要声明该对象。所以,不,你不能没有temp你的代码(除非你使用reduce而不是循环)。

More information on MDN:

有关 MDN 的更多信息:

  1. map: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
  2. reduce: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce
  1. 地图:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
  2. 减少:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce

回答by DanielEli

hmm.. looks like wrapping it in a function like this would do it.

嗯.. 看起来像将它包装在这样的函数中就可以了。

function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    if (arr[i] !== undefined) rv[arr[i]] = true;
  return rv;
}