compressing object hierarchies in JavaScript(在 JavaScript 中压缩对象层次结构)
问题描述
是否有一种通用方法可以将嵌套对象压缩"到单个级别:
Is there a generic approach to "compressing" nested objects to a single level:
var myObj = {
a: "hello",
b: {
c: "world"
}
}
compress(myObj) == {
a: "hello",
b_c: "world"
}
我想这会涉及到一些递归,但我认为我不需要在这里重新发明轮子......!?
I guess there would be some recursion involved, but I figured I don't need to reinvent the wheel here... !?
推荐答案
function flatten(obj, includePrototype, into, prefix) {
into = into || {};
prefix = prefix || "";
for (var k in obj) {
if (includePrototype || obj.hasOwnProperty(k)) {
var prop = obj[k];
if (prop && typeof prop === "object" &&
!(prop instanceof Date || prop instanceof RegExp)) {
flatten(prop, includePrototype, into, prefix + k + "_");
}
else {
into[prefix + k] = prop;
}
}
}
return into;
}
您可以通过将 true
传递给第二个参数来包含继承成员.
You can include members inherited members by passing true
into the second parameter.
一些注意事项:
递归对象不起作用.例如:
recursive objects will not work. For example:
var o = { a: "foo" };
o.b = o;
flatten(o);
会递归直到抛出异常.
就像 ruquay 的回答一样,这会像普通对象属性一样提取数组元素.如果要保持数组完整,请将|| prop instanceof Array
"添加到异常中.
Like ruquay's answer, this pulls out array elements just like normal object properties. If you want to keep arrays intact, add "|| prop instanceof Array
" to the exceptions.
如果您从不同的窗口或框架对对象调用此方法,日期和正则表达式将不包括在内,因为 instanceof
将无法正常工作.您可以通过将其替换为默认的 toString 方法来解决此问题,如下所示:
If you call this on objects from a different window or frame, dates and regular expressions will not be included, since instanceof
will not work properly. You can fix that by replacing it with the default toString method like this:
Object.prototype.toString.call(prop) === "[object Date]"
Object.prototype.toString.call(prop) === "[object RegExp]"
Object.prototype.toString.call(prop) === "[object Array]"
这篇关于在 JavaScript 中压缩对象层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JavaScript 中压缩对象层次结构


- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01