Javascript 在 CoffeeScript 中将对象数组映射到键/值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8348584/
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-08-24 05:38:22  来源:igfitidea点击:

Mapping an array of objects to key/value pairs in CoffeeScript

javascriptjquerycoffeescript

提问by Thilo-Alexander Ginkel

I have an array of elements that I would like to apply a mapping to to convert it into key value pairs on a single object (to mimic an associative array).

我有一个元素数组,我想对其应用映射以将其转换为单个对象上的键值对(以模拟关联数组)。

The approach in Can destructuring assignment be used to effect a projection in CoffeeScript?does not seem to work for me as it results in a simple array instead of key/value pairs.

Can destructuring assignment 中的方法可以用于影响 CoffeeScript 中的投影吗?似乎对我不起作用,因为它导致一个简单的数组而不是键/值对。

My language of choice is CoffeeScript or JavaScript.

我选择的语言是 CoffeeScript 或 JavaScript。

An example:

一个例子:

[{name: 'a', value: 'b', other: 'c'}, {name: 'd', value: 'e', other: 'f'}]

is supposed to be transformed into:

应该转换为:

{
  a: 'b',
  d: 'e'
}

One-liners are preferred. ;-)

优选单衬。;-)

采纳答案by Jonathan Lonowski

To fix the syntax error, you'll have to expand { @name: @value }to:

要修复语法错误,您必须扩展{ @name: @value }为:

o = {}; o[@name] = @value; o

You can then merge the objects with $.extend()and a splat (with the empty object to avoid accidentally extending jQuery):

然后,您可以使用$.extend()和 splat合并对象(使用空对象以避免意外扩展 jQuery):

$.extend {}, $(row).children('input').map(() -> o = {}; o[@name] = @value; o)...

Though, a simpler option would be just to use a 2-liner:

不过,一个更简单的选择就是使用 2-liner:

result = {}
$(row).children('input').each(() -> result[@name] = @value)

回答by Zirak

var arr = [{name: 'a', value: 'b', other: 'c'}, {name: 'd', value: 'e', other: 'f'}];

var obj = arr.reduce(function ( total, current ) {
    total[ current.name ] = current.value;
    return total;
}, {});

Pure javascript. It's practically a one liner, and it looks hawt.

纯javascript。它实际上是一个单衬里,看起来很结实。

Array.prototype.reduceis ES5, but isn't difficult to shim. Here's an example shim:

Array.prototype.reduce是 ES5,但不难填充。这是一个示例垫片:

Array.prototype.reduce = function ( fun, initVal ) {
    var sum = initVal || this[ 0 ],
        i = 1, len = this.length;

    do {
        sum = fun.call( undefined, sum, this[i], i, this );
    } while ( ++i < len );

    return sum;
};

arr.reduceis a sophisticated version of arr.map, which is a sophisticated version of arr.forEach. You can do this for the same effect:

arr.reduce是 的复杂版本arr.map,这是 的复杂版本arr.forEach。您可以这样做以达到相同的效果:

var obj = {};
arr.forEach(function ( val ) {
    obj[ val.name ] = val.value;
});

//and using jQuery.each
var obj = {};
$.each( arr, function ( index, val ) {
    obj[ val.name ] = val.value;
});

//latter version in coffeescript:
obj = {}
$.each( arr, (index, val) ->
    obj[ val.name ] = val.value
)

回答by Ricardo Tomasi

values = {}
values[name] = value for {name, value} in arr

or in javascript:

或在 javascript 中:

var values = {}
arr.forEach(function(o){
    values[o.name] = o.value
})

Which is almost exactly what the CoffeeScript one compiles to.

这几乎就是 CoffeeScript 编译的结果。

回答by Tieme

Or using plain ES6:

或者使用普通的 ES6:

const old = [
  {name: 'a', value: 'b', other: 'c'}, 
  {name: 'd', value: 'e', other: 'f'}
]

const transformed = Object.assign(
  {}, 
  ...old.map(({name, value}) => ({ [name]: value }))
);

console.log(transformed);

回答by Onato

Using Array.prototype.reduce():

使用Array.prototype.reduce()

var arrayOfObjects = [
              {name: 'a', value: 'b', other: 'c'}, 
              {name: 'd', value: 'e', other: 'f'}
            ];

arrayOfObjects.reduce(function(previousValue, currentValue, currentIndex) {
  previousValue[currentValue.name] = currentValue.value;
  return previousValue;
}, {})

回答by ducaale

ES6 one-liner:

ES6 单线:

const data = [{name: 'a', value: 97}, {name: 'b', value: 98}]

data.reduce((obj, e) => ({...obj, [e.name]: e.value}), {})

回答by rwitzel

Have a look at http://coffeescriptcookbook.com/chapters/arrays/creating-a-dictionary-object-from-an-array

看看http://coffeescriptcookbook.com/chapters/arrays/creating-a-dictionary-object-from-an-array

  myArray = [{name: 'a', value: 'b', other: 'c'}, {name: 'd', value: 'e', other: 'f'}]
  dict = {}
  dict[obj['name']] = obj['value'] for obj in myArray when obj['name']?
  console.log(JSON.stringify(dict, 0, 2));

This produces exactly what you want.

这正是您想要的。