最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
使用javascript#forEach可以做到这一点
var result = {},
attributes = ['a', 'b','c'];
attributes.forEach(function(prop,index) {
result[index] = prop;
});
ECMA6:
attributes.forEach((prop,index)=>result[index] = prop);
其他回答
这是一个解决方案在coffeescript
arrayToObj = (arr) ->
obj = {}
for v,i in arr
obj[i] = v if v?
obj
下面的方法将数组转换为具有特定给定键的对象。
/**
* Converts array to object
* @param {Array} array
* @param {string} key (optional)
*/
Array.prototype.ArrayToObject = function(key) {
const array = this;
const obj = {};
array.forEach((element, index) => {
if(!key) {
obj[index] = element;
} else if ((element && typeof element == 'object' && element[key])) {
obj[element[key]] = element;
}
});
return obj;
}
前任-
[{名称:“测试”},{名称:test1的}].ArrayToObject(“名字”);
会给
{test: {name: 'test'}, test1: {name: 'test1'}}
并且incase key没有作为参数提供给该方法
i.e. [{name: 'test'}, {name: 'test1'}].ArrayToObject();
会给
{0: {name: 'test'}, 1: {name: 'test1'}}
如果数组包含2元素数组,其中第一个元素是键,第二个元素是值,您可以使用reduce轻松地将其转换为对象。
[
["key1","value1"],
["key2", "value2"],
["key3", "value3"]
]
.reduce((acc, [key, value])=>({...acc, [key]: value}), {});
结果:
{
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
最短的答案:(使用解构)
const obj = { ...input }
例子:
const inputArray = ["a", "b", "c"]
const outputObj = { ...inputArray }
我们可以使用Object。赋值和数组。reduce函数将数组转换为对象。 Var arr = [{a:{b:1}},{c:{d:2}}] var newObj = arr。reduce((a, b) =>对象。赋值(a, b), {}) console.log (newObj)