在javascript中将字符串转换为对象

时间:2015-03-22 15:11:26

标签: javascript string split

我需要转换一个字符串

1. "user.member.staffAddress"
2. "user.something"

对象:

1. { user: { member: { staffAddress: {} } } }
2. { user: { something: {} } }

有没有人有一种优雅的方式怎么做?它应该始终是对象中的对象。最后一个属性应该是空的。

3 个答案:

答案 0 :(得分:1)

我写了一个实用程序,我认为你会发现这有用: https://github.com/forms-js/forms-js/blob/master/source/utils/flatten.ts

这是相关的比特。它是用TypeScript编写的,但如果删除:type annotations,它就是有效的JavaScript。

/**
 * Writes a value to the location specified by a flattened key and creates nested structure along the way as needed.
 *
 * <p>For example, writing "baz" to the key 'foo.bar' would result in an object <code>{foo: {bar: "baz"}}</code>.
 * Writing 3 to the key 'foo[0].bar' would result in an object <code>{foo: [{bar: 3}]}</code>.
 */
function write(value:any, flattenedKey:string, object:any):void {
  var currentKey:any;
  var keyIndexStart = 0;

  for (var charIndex = 0, length = flattenedKey.length; charIndex < length; charIndex++) {
    var character = flattenedKey.charAt(charIndex);

    switch(character) {
      case '[':
        currentKey = flattenedKey.substring(keyIndexStart, charIndex);

        createPropertyIfMissing_(currentKey, object, Array);
        break;
      case ']':
        currentKey = flattenedKey.substring(keyIndexStart, charIndex);
        currentKey = parseInt(currentKey); // Convert index from string to int

        // Special case where we're targeting this object in the array
        if (charIndex === length - 1) {
          object[currentKey] = value;
        } else {

          // If this is the first time we're accessing this Array key we may need to initialize it.
          if (!object[currentKey] && charIndex < length - 1) {
            switch(flattenedKey.charAt(charIndex + 1)) {
              case '[':
                object[currentKey] = [];
                break;
              case '.':
                object[currentKey] = {};
                break;
            }
          }

          object = object[currentKey];
        }
        break;
      case '.':
        currentKey = flattenedKey.substring(keyIndexStart, charIndex);

        // Don't do anything with empty keys that follow Array indices (e.g. anArray[0].aProp)
        if (currentKey) {
          createPropertyIfMissing_(currentKey, object, Object);
        }
        break;
      default:
        continue; // Continue to iterate...
        break;
    }

    keyIndexStart = charIndex + 1;

    if (currentKey) {
      object = object[currentKey];
    }
  }

  if (keyIndexStart < flattenedKey.length) {
    currentKey = flattenedKey.substring(keyIndexStart, flattenedKey.length);

    object[currentKey] = value;
  }
}

/**
 * Helper method for initializing a missing property.
 *
 * @throws Error if unrecognized property specified
 * @throws Error if property already exists of an incorrect type
 */
function createPropertyIfMissing_(key:string, object:any, propertyType:any):void {
  switch(propertyType) {
    case Array:
      if (!object.hasOwnProperty(key)) {
        object[key] = [];
      } else if (!(object[key] instanceof Array)) {
        throw Error('Property already exists but is not an Array');
      }
      break;
    case Object:
      if (!object.hasOwnProperty(key)) {
        object[key] = {};
      } else if (typeof object[key] !== 'object') {
        throw Error('Property already exists but is not an Object');
      }
      break;
    default:
      throw Error('Unsupported property type');
      break;
  }
}

公平地说,你也可以考虑一个专门写 的项目来做这件事 - 而不是我的,这只是一小部分 - 也就是说,https://github.com/hughsk/flat

答案 1 :(得分:0)

迭代并添加属性等......

function stringToObject(str) {
    var obj = {}, arr = str.split('.');
    
    (function it(o) {
        var key = arr.shift();
        o[key] = {};
        if (arr.length) it(o[key]);
    }(obj));
    
    return obj;
}

var obj = stringToObject("user.member.staffAddress");

document.body.innerHTML = JSON.stringify(obj, null, 4);

答案 2 :(得分:0)

字符串转换方法:

var str = 'user.member.staffAddress'
var str_arr = str.split('.')
var obj = JSON.parse(
    '{ "' + str_arr.join('": { "') + '": {}' 
    + Array(str_arr.length+1).join(' }')
)
console.log(obj)
// { "user": { "member": { "staffAddress": {} } } }
  1. 拆分字符串。
  2. 使用": { "加入元素。
  3. { "": {}换取新字符串,后跟length个大括号。
  4. 将最终字符串解析为JSON对象。
  5. JSFiddle Demo