【问题标题】:object.entries in ES5/Vanila javascriptES5/Vanilla javascript 中的 object.entries
【发布时间】:2020-08-26 10:50:43
【问题描述】:

我有一个下面的对象。

{name: 'Ryan', Height: '5.6cm'}

在 ES6 中,我们有 Object.prototype.entries(),它将以数组的形式返回密钥对值。同样对于 Object.prototype.values() 将返回值数组。

谁能帮助我在不使用Object.entries 和不使用Object.values() 的情况下如何在 ES5 javascript 中实现相同的功能?

【问题讨论】:

  • Object.keys() 是 ES5 afaik。

标签: ecmascript-6 ecmascript-5


【解决方案1】:

@Sirko answered this with his comment,可以使用 Object.keys() 替换 Object.entries():

var entriesObj = {name: 'Ryan', Height: '5.6cm'};
// var output = Object.entries(entriesObj).reduce((collector, [key, value]) => {
var output = Object.keys(entriesObj).reduce(function (collector, key) {
  var value = entriesObj[key];
  return Object.assign({}, collector, {
    [key]: 'modified' + value,
  });
}, {});
console.log(output); // {name: "modifiedRyan", Height: "modified5.6cm"}

出于某种原因,我的 PhantomJS 构建没有 Object.entries,但有 Object.assign。您还可以使用for...in 来遍历对象属性(我认为这是最古老的方法)。

【讨论】:

    【解决方案2】:

    您可以使用 core.js 之类的 polyfill 库来导入您想要使用的 polyfill,然后您可以在代码中使用 ES6 方法。

    如果你只想要一个一次性的功能,你也可以在例如找到 polyfills。 MDN。

    对于Object.prototype.entries(),这将给出:

    if (!Object.entries) {
      Object.entries = function( obj ){
        var ownProps = Object.keys( obj ),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array
        while (i--)
          resArray[i] = [ownProps[i], obj[ownProps[i]]];
        
        return resArray;
      };
    }
    

    如果您不想将其添加到 Object 范围内,可以将其更改为您自己的函数名称。

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 2019-11-18
      • 2017-02-28
      相关资源
      最近更新 更多