How to remove all getters and setters from an object in Javascript and keep pure value

依然范特西╮ 提交于 2019-12-11 05:05:20

问题


I'm using a library called which takes a JS object as an input. Unfortunately, the JSONP api that I am using returns an object containing getters and setters, which this particular library does not know how to handle.

How can I remove all getters and setters from an object while retaining the values of the properties, so I have a Plain Old JavaScript Object?


回答1:


a solution for this special case/environment/setting might look like that ...

var
  obj = JSON.parse(JSON.stringify(model));

console.log("obj before : ", obj);

Object.keys(obj).reduce(function (obj, key) {

  if (obj["_" +  key] === obj[key]) {
    delete obj["_" +  key];
  }
  return obj;

}, obj);

console.log("obj after : ", obj);

see also ... http://jsfiddle.net/w23uLttu/8/




回答2:


After trying all sorts of things such as serializing to JSON and back, I ended up writing a simple shallowClone function to handle this:

const shallowClone = (obj) => {
  return Object.keys(obj).reduce((clone, key) => {
    clone[key] = obj[key];
    return clone;
  }, {});
}



回答3:


Use getOwnPropertyDescriptors to get all the current descriptors, find those with get property, and redefine them. However, you will only be able to do this if the property is configurable.

const descriptors = Object.getOwnPropertyDescriptors(obj);

Object.keys(descriptors)
  .filter(key => descriptors[key].get)
  .forEach(key => Object.defineProperty(obj, key, {value: obj[key]}));

Object.getOwnPropertyDescriptors is an ES7 proposal. Meanwhile, here's an implementation from here:

function getOwnPropertyDescriptors(obj) {
  const result = {};
  for (let key of Reflect.ownKeys(obj)) {
      result[key] = Object.getOwnPropertyDescriptor(obj, key);
  }
  return result;
}


来源:https://stackoverflow.com/questions/39875871/how-to-remove-all-getters-and-setters-from-an-object-in-javascript-and-keep-pure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!