最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
这是一个解决方案在coffeescript
arrayToObj = (arr) ->
obj = {}
for v,i in arr
obj[i] = v if v?
obj
其他回答
这里没有多少人评论Object.fromEntries,我真的很喜欢它,因为它更干净,很容易与TypeScript一起工作,不需要太多泛型类型和东西。如果需要,它还允许使用map自定义键。缺点:如果你想要一个自定义键,你将需要一个额外的映射。例如:
const tags = [
{ name: 'AgeGroup', value: ageGroup },
{ name: 'ApparelTypes', value: apparelTypes },
{ name: 'Brand', value: brand },
// ...
]
const objectTags = Object.fromEntries(tags.map((t) => [t.name, t.value]))
/*
{
AgeGroup: 'Adult',
Apparel: 'Creeper, Jacket'
Brand: '',
// ...
}
*/
import books from "./books.json";
export const getAllBooks = () => {
return {
data: books,
// a=accoumulator, b=book (data itelf), i=index
bookMap: books.reduce((a, book, i) => {
// since we passed {} as initial data, initially a={}
// {bookID1:book1, bookID2:i}
a[book.id] = book;
// you can add new property index
a[book.id].index=i
return a;
// we are passing initial data structure
}, {}),
};
};
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
const nodes = {
node1: {
interfaces: {if1: {}, if2: {}}
},
node2: {
interfaces: {if3: {}, if4: {}}
},
node3: {
interfaces: {if5: {}, if6: {}}
},
}
解决方案是结合使用reduce和对象扩展:
const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
我曾多次遇到过这个问题,并决定编写一个尽可能通用的函数。看一看,可以随意修改吗
function typeOf(obj) {
if ( typeof(obj) == 'object' ) {
if (obj.length)
return 'array';
else
return 'object';
} else
return typeof(obj);
}
function objToArray(obj, ignoreKeys) {
var arr = [];
if (typeOf(obj) == 'object') {
for (var key in obj) {
if (typeOf(obj[key]) == 'object') {
if (ignoreKeys)
arr.push(objToArray(obj[key],ignoreKeys));
else
arr.push([key,objToArray(obj[key])]);
}
else
arr.push(obj[key]);
}
}else if (typeOf(obj) == 'array') {
for (var key=0;key<obj.length;key++) {
if (typeOf(obj[key]) == 'object')
arr.push(objToArray(obj[key]));
else
arr.push(obj[key]);
}
}
return arr;
}
一个快速而肮脏的问题:
var obj = {},
arr = ['a','b','c'],
l = arr.length;
while( l && (obj[--l] = arr.pop() ) ){};