基于一次性钥匙展平

时间:2015-05-21 17:36:26

标签: javascript json underscore.js

使用

{ _id: "123", super: { super: { super: { someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}}}}

超级密钥的水平可以任意深度,我喜欢它们中的每一个和它们的内容被展平,以便得到

{ _id: "123", someString: "here", someOtherString: "here", someObject: { withSomeContents: true }}

这样做的好方法是什么?最好使用下划线。

1 个答案:

答案 0 :(得分:3)

您需要递归地合并对象,同时检查所需的密钥:



var data = {
  _id: "123",
  super: {
    super: {
      super: {
        someString: "here",
        someOtherString: "here",
        someObject: {
          withSomeContents: true
        }
      }
    }
  }
};

function merge(dest, src) {
  Object.keys(src).forEach(function(key) {
    dest[key] = src[key];
  });
}

function flattenKey(data, flatKey) {
  return Object.keys(data).reduce(function(obj, key) {
    if (key === flatKey) {
      merge(obj, flattenKey(data[key], flatKey));
    } else {
      obj[key] = data[key];
    }
    return obj;
  }, {});
}

document.getElementById('r').textContent = JSON.stringify(flattenKey(data, 'super'));

<pre id=r></pre>
&#13;
&#13;
&#13;