什么是最好的转换方式:
['a','b','c']
到:
{
0: 'a',
1: 'b',
2: 'c'
}
['a','b','c']
到:
{
0: 'a',
1: 'b',
2: 'c'
}
const arr = ['a','b','c'];
let obj = {}
function ConvertArr(arr) {
if (typeof(arr) === 'array') {
Object.assign(obj, arr);
}
这种方式只有在它是数组的情况下才会运行,但是你可以使用 let 全局对象变量或不使用,这取决于你自己,如果你不使用 let,只需执行 Object.assign({}, arr)。
如果您喜欢简洁明了的代码,并且IE8不再是问题(就像它应该一样)
['a','b','c'].reduce((m,e,i) => Object.assign(m, {[i]: e}), {});
请在浏览器控制台上尝试运行
可以像这样更详细地显示:
['a','b','c'].reduce(function(memo,elm,idx) {
return Object.assign(memo, {[idx]: elm});
}, {});
但仍然排除IE8。如果必须使用IE8,则可以像这样使用lodash/underscore:
_.reduce(['a','b','c'], function(memo,elm,idx) {
return Object.assign(memo, {[idx]: elm});
}, {})
You could use a function like this:
var toObject = function(array) {
var o = {};
for (var property in array) {
if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
o[i] = array[i];
}
}
return o;
};
虽然与此无直接关系,但我在这里搜索一行代码来合并嵌套对象,例如
const nodes = {
node1: {
interfaces: {if1: {}, if2: {}}
},
node2: {
interfaces: {if3: {}, if4: {}}
},
node3: {
interfaces: {if5: {}, if6: {}}
},
}
const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
Object.fromEntries(Object.entries(nodes).map(([key, value] => [key, value.interfaces]))
- Jeff Fairley /**
* 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;
}
例如 -
[{name: 'test'}, {name: 'test1'}].ArrayToObject('name');
将会得到
{test: {name: 'test'}, test1: {name: 'test1'}}
如果方法没有提供参数作为关键字
i.e. [{name: 'test'}, {name: 'test1'}].ArrayToObject();
{0: {name: 'test'}, 1: {name: 'test1'}}
arrayToObj = (arr) ->
obj = {}
for v,i in arr
obj[i] = v if v?
obj
obj[i] = v for v,i in arr when v?
- XåpplI'-I0llwlg'I -var newObj = {};
angular.extend(newObj, ['a','b','c']);
我会使用下划线来实现这个,但如果不可用,我会降级到使用 reduce 函数,并将初始值设为空对象 {}
>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}
现在大多数浏览器都应该可以使用reduce函数,详情请参见MDN
reduce()
的编辑是在2014年3月12日添加的,早于您的回答发布时间。 - Cristik使用JavaScript的reduce方法非常简单:
["a", "b", "c", "d"].reduce(function(previousValue, currentValue, index) {
previousValue[index] = currentValue;
return previousValue;
},
{}
);
Typescript解决方案:
export const toMap = (errors: ResponseError[]) => {
const errorMap: Record<string, string> = {};
errors.forEach(({ field, message }) => {
errorMap[field] = message;
});
return errorMap;
};
export type FieldError = {
field: string;
message: string;
};
_.keyBy
(以前称为_.indexBy
):https://lodash.com/docs#keyBy - 2540625_.toPlainObject
。例如:var myObj = _.toPlainObject(myArr)
。 - julian soro