mongodb 数组化简

    技术2022-07-11  163

    mongodb 数组化简

    Every developer who specializes in any programming language will tell you there's a powerful tool the language provides that they rarely use and wish they knew more about. For me, it's Array.prototype.reduce. I quite enjoy the other Array methods like map, filter, and find, but reduce is one that I knew was powerful but never really had much use for.

    每个专门研究任何编程语言的开发人员都会告诉您,有一个功能强大的工具,该语言提供了他们很少使用并且希望他们了解更多的工具。 对我来说,它是Array.prototype.reduce 。 我非常喜欢其他Array方法,例如map , filter和find ,但是reduce是我知道功能强大但从未真正使用过的方法。

    It wasn't until I was refactoring some of the Firefox DevTools Debugger code that I found a great use case for reduce -- one I plan on using in the future.

    直到我重构了一些Firefox DevTools Debugger代码后 ,我才发现了一个很好的reduce使用案例-我计划在将来使用。

    Methods like forEach and map were created to avoid side effects, and reduce is no exception. In this case, however, reduce can return an Object other than an Array. Take this case for example:

    创建了诸如forEach和map方法来避免副作用 ,并且reduce也不例外。 在这种情况下,然而, reduce可以返回一个Object不是其他Array 。 以这种情况为例:

    // Samples sources const sources = [ { id: "server1.conn13.child1/39", url: "https://davidwalsh.name/" }, { id: "server1.conn13.child1/37", url: "https://davidwalsh.name/util.js" } ]; // Return an object of sources with the keys being "id" const sourcesMap = sources.reduce((map, source) => { map[source.id] = source return map; }, {});

    In the example above, we take an array of Source objects and return a single object literal with each Source's id as the key:

    在上面的示例中,我们获取一个Source对象数组,并返回一个对象常量,其中每个Source的id作为键:

    { "server1.conn13.child1/39": { "id": "server1.conn13.child1/39", "url": "https://davidwalsh.name/" }, "server1.conn13.child1/37": { "id": "server1.conn13.child1/37", "url": "https://davidwalsh.name/util.js" } }

    Note that the {}, which is the last argument to reduce, is starting/default object to be returned. If there were no items in the array, {} would be returned. Also appreciate that an array method returns an object literal and not a modified array!

    注意, {}是reduce的最后一个参数,是要返回的起始对象/默认对象。 如果数组中没有项目,将返回{} 。 还应该意识到,数组方法返回的是对象常量而不是修改后的数组!

    It's crazy that I've not used reduce more, but that's just life in our industry -- we all have a few APIs we just haven't used much of. What feature of JavaScript have you frequently seen but not used?

    疯狂的是我没有使用过reduce更多的东西,但这只是我们行业中的生活-我们都有一些API,我们只是很少使用。 您经常看到但不使用JavaScript的哪些功能?

    翻译自: https://davidwalsh.name/using-array-reduce

    mongodb 数组化简

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.009, SQL: 9