最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
下面的方法将数组转换为具有特定给定键的对象。
/**
* 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'}}
其他回答
一个简单和厚脸皮的方法,快速转换数组的项目到一个对象
function arrayToObject( srcArray ){
return JSON.parse( JSON.stringify( srcArray ) );
}
然后像这样使用它…
var p = [0,2,3,'pork','pie',6];
obj = new arrayToObject( p );
console.log( obj[3], obj[4] )
// expecting `pork pie`
输出:
pork pie
检查类型:
typeof obj
"object"
如果没有原型方法,事情就不完整
Array.prototype.toObject =function(){
return JSON.parse( JSON.stringify( this ) );
}
使用:
var q = [0,2,3,'cheese','whizz',6];
obj = q.toObject();
console.log( obj[3], obj[4] )
// expecting `cheese whizz`
输出:
cheese whizz
*注意,没有命名例程,所以如果你想要特定的名称,那么你将需要继续使用下面现有的方法。
老的方法
这允许您从一个数组生成一个对象,其中的键是按照您想要的顺序定义的。
Array.prototype.toObject = function(keys){
var obj = {};
var tmp = this; // we want the original array intact.
if(keys.length == this.length){
var c = this.length-1;
while( c>=0 ){
obj[ keys[ c ] ] = tmp[c];
c--;
}
}
return obj;
};
result = ["cheese","paint",14,8].toObject([0,"onion",4,99]);
Console.log (">>>:" + result.onion);将输出"paint",函数必须有相等长度的数组,否则将得到一个空对象。
这里是一个更新的方法
Array.prototype.toObject = function(keys){
var obj = {};
if( keys.length == this.length)
while( keys.length )
obj[ keys.pop() ] = this[ keys.length ];
return obj;
};
这是一个解决方案在coffeescript
arrayToObj = (arr) ->
obj = {}
for v,i in arr
obj[i] = v if v?
obj
尝试使用反射从数组项复制到对象。
var arr =['aa:23','bb:44','cc:55']
var obj ={}
arr.forEach(e => {
var ee = e.split(':')
Reflect.set(obj,ee[0],ee[1])
});
console.log(obj) // { aa: '23', bb: '44', cc: '55' }
最简单的方法如下:
const arr = ['a','b','c'];
let obj = {}
function ConvertArr(arr) {
if (typeof(arr) === 'array') {
Object.assign(obj, arr);
}
这样它只在数组中运行,然而,你可以用let全局对象变量或不带,这取决于你,如果你不带let,只运行object。加勒比海盗,分配({})。
使用javascript lodash库。有一个简单的方法 _。[iteratee = _.identity] mapKeys(对象) 可以进行转换。