如何将这个嵌套对象转换为扁平对象?

shr*_*kuu 8 javascript jquery

对不起,我不知道怎么用短语来标题.请尽可能帮助编辑.

我有一个像这样的对象:

{
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想让它看起来像:

{
    'a': 'jack',
    'b.c': 'sparrow',
    'b.d.e': 'hahaha'
}

// so that I can use it this way:
a['b.d.e']
Run Code Online (Sandbox Code Playgroud)

jQuery也可以.我知道嵌套对象,我可以用a.b.d.e得到hahaha,但是今天我不得不使用它像a['b.d.e']-_- !!! 我怎样才能做到这一点?提前致谢 :)

Mar*_*rie 18

您可以使用递归函数来抓取对象并为您展平它.

var test = {
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
            e: 'hahaha'
        }
    }
};

function dive(currentKey, into, target) {
    for (var i in into) {
        if (into.hasOwnProperty(i)) {
            var newKey = i;
            var newVal = into[i];
            
            if (currentKey.length > 0) {
                newKey = currentKey + '.' + i;
            }
            
            if (typeof newVal === "object") {
                dive(newKey, newVal, target);
            } else {
                target[newKey] = newVal;
            }
        }
    }
}

function flatten(arr) {
    var newObj = {};
    dive("", arr, newObj);
    return newObj;
}

var flattened = JSON.stringify(flatten(test));
console.log(flattened);
Run Code Online (Sandbox Code Playgroud)


zur*_*fyx 9

另一种递归实现。我只是想自己编写一个实现,即使当前的实现已经非常好。

递归函数检查键是否为 类型'object'

  • 如果它是一个对象,我们按每个对象的键进行迭代。
  • 否则,我们将它添加到我们的结果对象中。
function flat(res, key, val, pre = '') {
  const prefix = [pre, key].filter(v => v).join('.');
  return typeof val === 'object'
    ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
    : Object.assign(res, { [prefix]: val});
}
return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
Run Code Online (Sandbox Code Playgroud)

扁平 NPM 包

或者你可以简单地使用flat npm package,这是一个众所周知的测试库。

var flatten = require('flat')
flatten(obj);
Run Code Online (Sandbox Code Playgroud)

? 我会在严肃的代码中使用它。

[Extra] 更简洁地调用上述函数

function flatObject(input) {
  function flat(res, key, val, pre = '') {
    const prefix = [pre, key].filter(v => v).join('.');
    return typeof val === 'object'
      ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
      : Object.assign(res, { [prefix]: val});
  }

  return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
}

const result = flatObject(input);
Run Code Online (Sandbox Code Playgroud)

[额外] 演示

http://codepen.io/zurfyx/pen/VpErja?editors=1010

function flat(res, key, val, pre = '') {
  const prefix = [pre, key].filter(v => v).join('.');
  return typeof val === 'object'
    ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
    : Object.assign(res, { [prefix]: val});
}
return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
Run Code Online (Sandbox Code Playgroud)
var flatten = require('flat')
flatten(obj);
Run Code Online (Sandbox Code Playgroud)


Lew*_*wis 6

递归是这种情况的最佳解决方案。

function flatten(input, reference, output) {
  output = output || {};
  for (var key in input) {
    var value = input[key];
    key = reference ? reference + '.' + key : key;
    if (typeof value === 'object' && value !== null) {
      flatten(value, key, output);
    } else {
      output[key] = value;
    }
  }
  return output;
}
var result = flatten({
  a: 'jack',
  b: {
    c: 'sparrow',
    d: {
      e: 'hahaha'
    }
  }
});
document.body.textContent = JSON.stringify(result);
Run Code Online (Sandbox Code Playgroud)


adi*_*iga 6

您可以遍历对象的条目。如果value是对象,则递归调用该函数。使用flatMap获得条目的扁平阵列。

然后使用Object.fromEntries()从扁平的条目数组中获取一个对象

const input = {
  a: 'jack',
  b: {
    c: 'sparrow',
    d: {
      e: 'hahaha'
    }
  }
}

const getEntries = (o, prefix = '') => 
  Object.entries(o).flatMap(([k, v]) => 
    Object(v) === v  ? getEntries(v, `${prefix}${k}.`) : [ [`${prefix}${k}`, v] ]
  )

console.log(
  Object.fromEntries(getEntries(input))
)
Run Code Online (Sandbox Code Playgroud)

注意:仅Object(v) === v返回true对象。typeof v === 'object'也是如此v = null