将数组转换为对象属性JavaScript

时间:2015-03-20 17:47:46

标签: javascript arrays object properties

我有一个对象:

{
    messages: {
        foo: {
            bar: "hello"
        },
        other: {
            world: "abc"
        }
    }
}

我需要一个功能:

var result = myFunction('messages.foo.bar'); // hello

如何创建此功能?

由于

1 个答案:

答案 0 :(得分:1)

我在这里编写了一组实用函数: https://github.com/forms-js/forms-js/blob/master/source/utils/flatten.ts

还有Flat库: https://github.com/hughsk/flat

要么适合您的需要。基本上它归结为这样的事情:

function read(key, object) {
  var keys = key.split(/[\.\[\]]/);

  while (keys.length > 0) {
    var key = keys.shift();

    // Keys after array will be empty
    if (!key) {
      continue;
    }

    // Convert array indices from strings ('0') to integers (0)
    if (key.match(/^[0-9]+$/)) {
      key = parseInt(key);
    }

    // Short-circuit if the path being read doesn't exist
    if (!object.hasOwnProperty(key)) {
      return undefined;
    }

    object = object[key];
  }

  return object;
}