ES5 / Vanila javascript中的object.entries

问题描述

我有一个下面的物体。

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

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

任何人都可以在不使用Object.entries和不使用Object.values()的情况下帮助我了解如何在ES5 javascript中实现相同的功能吗?

解决方法

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

如果您只想要一次性功能,也可以在例如上找到填充。 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;
  };
}

如果您不想将其添加到对象范围,则可以对其稍作更改。

,

@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 遍历对象属性(我认为这是最古老的方法)。