ASfdsa33 ASfdsa33 - 1 month ago 20
TypeScript Question

.map() on javascript objects

is there a way to map my

window._someProp
like if I would do it in TypeScript/Knockout:

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


Wha's the best way in plain JavaScript or Jquery ?!

Answer

There are many ways to loop through an object's properties.

You could use the Object.keys method and Object.assign to extend an object's properties.

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);

To map an array, use Array.prototype.map. E.g.: [1,2,3].map(function(v) { return v * 2; }) produces a new array [2,4,6].

Comments