[英]Mapping an array of objects to key/value pairs in CoffeeScript
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? Can destructuring assign中的方法可用于在CoffeeScript中实现投影? does not seem to work for me as it results in a simple array instead of key/value pairs.
似乎不适合我,因为它导致一个简单的数组而不是键/值对。
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. 单线是首选。 ;-)
;-)
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. 纯粹的javascript。 It's practically a one liner, and it looks hawt.
它实际上只是一个衬垫,它看起来很重要。
Array.prototype.reduce is ES5, but isn't difficult to shim. Array.prototype.reduce是ES5,但不难以垫片。 Here's an example shim:
这是一个示例垫片:
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.reduce
is a sophisticated version of arr.map
, which is a sophisticated version of arr.forEach
. arr.reduce
是一个复杂的版本arr.map
,这是一个复杂的版本arr.forEach
。 You can do this for the same effect: 你可以这样做同样的效果:
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
)
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编写的内容。
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(使用空对象$.extend()
合并对象以避免意外扩展jQuery:
$.extend {}, $(row).children('input').map(() -> o = {}; o[@name] = @value; o)...
Though, a simpler option would be just to use a 2-liner: 但是,更简单的选择就是使用2线:
result = {}
$(row).children('input').each(() -> result[@name] = @value)
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);
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;
}, {})
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. 这产生了你想要的。
ES6 one-liner: ES6单线:
const data = [{name: 'a', value: 97}, {name: 'b', value: 98}]
data.reduce((obj, e) => ({...obj, [e.name]: e.value}), {})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.