Thi*_*kel 29 javascript jquery coffeescript
我有一个元素数组,我想应用一个映射来将它转换为单个对象上的键值对(模仿一个关联数组).
Can destructuring assign中的方法可用于在CoffeeScript中实现投影吗?似乎不适合我,因为它导致一个简单的数组而不是键/值对.
我选择的语言是CoffeeScript或JavaScript.
一个例子:
[{name: 'a', value: 'b', other: 'c'}, {name: 'd', value: 'e', other: 'f'}]
Run Code Online (Sandbox Code Playgroud)
应该被转化为:
{
a: 'b',
d: 'e'
}
Run Code Online (Sandbox Code Playgroud)
单线是首选.;-)
Zir*_*rak 78
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;
}, {});
Run Code Online (Sandbox Code Playgroud)
纯粹的javascript.它实际上只是一个衬垫,它看起来很重要.
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;
};
Run Code Online (Sandbox Code Playgroud)
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
)
Run Code Online (Sandbox Code Playgroud)
Ric*_*asi 19
values = {}
values[name] = value for {name, value} in arr
Run Code Online (Sandbox Code Playgroud)
或者在javascript中:
var values = {}
arr.forEach(function(o){
values[o.name] = o.value
})
Run Code Online (Sandbox Code Playgroud)
这几乎就是CoffeeScript编写的内容.
Jon*_*ski 12
要修复语法错误,您必须扩展{ @name: @value }
为:
o = {}; o[@name] = @value; o
Run Code Online (Sandbox Code Playgroud)
然后,您可以将对象与$.extend()
splat 合并(使用空对象以避免意外扩展jQuery):
$.extend {}, $(row).children('input').map(() -> o = {}; o[@name] = @value; o)...
Run Code Online (Sandbox Code Playgroud)
但是,更简单的选择就是使用2线:
result = {}
$(row).children('input').each(() -> result[@name] = @value)
Run Code Online (Sandbox Code Playgroud)
Tie*_*eme 10
或者使用普通的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);
Run Code Online (Sandbox Code Playgroud)
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;
}, {})
Run Code Online (Sandbox Code Playgroud)