【问题标题】:How to Convert Array to Object with ordering change?如何通过更改顺序将数组转换为对象?
【发布时间】:2023-02-15 18:40:13
【问题描述】:

我有一个数组,现在想转换成带有顺序更改的对象。

我的代码:-

arr = [function() {}, new Object(), [], {}, NaN, Infinity, undefined, null, 0];

console.log({...arr});

但我想要如下格式的结果,我该如何实现?

OutPut: { function: 1, object: 4, number: 3, undefined: 1 }

感谢您的努力!

【问题讨论】:

  • 标题和问题似乎与您描述的输入/输出不匹配。 “排序”与在数组中创建类型计数有什么关系?

标签: javascript


【解决方案1】:

您可以计算类型。

const
    array = [function() {}, new Object(), [], {}, NaN, Infinity, undefined, null, 0],
    result = array.reduce((r, v) => {
        const type = typeof v;
        r[type] = (r[type] || 0) + 1;
        return r;
    }, {});

console.log(result);

【讨论】:

  • ??||
【解决方案2】:

您只需获取每个条目的 typeof 并将其汇总到一个对象中。

这是一个例子:

arr = [function() {}, new Object(), [], {}, NaN, Infinity, undefined, null, 0];

const obj = arr.map(e => typeof e).reduce((o,t) => ({...o, [t]: (o[t] ?? 0) + 1 }), {})
console.log(obj);

【讨论】:

    猜你喜欢
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    相关资源
    最近更新 更多