【问题标题】:.map() on javascript objects.map() 在 javascript 对象上
【发布时间】:2017-02-18 20:15:28
【问题描述】:

有没有办法映射我的window._someProp,就像我在 TypeScript/Knockout 中那样:

window._someProp.map(b => ko.mapping.fromJS(b, {}, new typescriptModule.CustomClass()))

在纯 JavaScript 或 Jquery 中最好的方法是什么?!

【问题讨论】:

标签: javascript jquery knockout.js typescript


【解决方案1】:

loop through an object's properties 有很多方法。

您可以使用Object.keys 方法和Object.assign 来扩展对象的属性。

var exampleExtend = function(obj) {
  Object.assign(obj, {
    extended: true
  });
};

var exampleObj = {
  first: {
    'a': 1
  },
  second: {
    'b': 2
  }
};

Object.keys(exampleObj)
      .forEach(function(k) { exampleExtend(exampleObj[k]); });

console.log(exampleObj);

map 一个数组,请使用Array.prototype.map。例如:[1,2,3].map(function(v) { return v * 2; }) 生成一个 new 数组 [2,4,6]

【讨论】:

  • 谢谢,但 Visual Studio 会显示使用 => 的语法错误...
  • 我已经重写了示例以使用常规函数而不是箭头函数。
猜你喜欢
  • 1970-01-01
  • 2016-09-23
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 2023-01-25
  • 1970-01-01
  • 2022-09-29
相关资源
最近更新 更多