将JavaScript数组转换为对象

时间:2015-09-16 22:11:04

标签: javascript arrays object

我有一个奇怪的要求将有效的javascript数组转换或转换为另一个javascript对象。

我收到了这种格式的服务器响应

{
"buyerPrimary.firstName":["The buyer primary.first name field is required."],
"buyerPrimary.lastName":["The buyer primary.last name field is required."]
}

我希望将此数组更改为此格式。

{
    "buyerPrimary":{
        "firstName":["The buyer primary.first name field is required."],
        "lastName":["The buyer primary.last name field is required."]
    }
}

仍然在JavaScript中苦苦挣扎,经过几个小时的搜索和尝试,我一直没有成功。非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

只需使用运算符[...]即可获取对象属性。

var sourceObject = {
  "buyerPrimary.firstName":["The buyer primary.first name field is required."],
  "buyerPrimary.lastName":["The buyer primary.last name field is required."]
};
var destinationObject = {
  "buyerPrimary":{
    "firstName":sourceObject["buyerPrimary.firstName"],
    "lastName":sourceObject["buyerPrimary.lastName"]
  }
};

答案 1 :(得分:0)

你拥有的是一个物体,而不是一个阵列。

您可以使用Object.keys获取对象自己的属性名称数组,然后使用reduce对其进行迭代以创建新对象。下面的代码应该有足够的评论,如果没有,请提出问题。

    var data = {
      "buyerPrimary.firstName":["The buyer primary.first name field is required."],
      "buyerPrimary.lastName":["The buyer primary.last name field is required."]
    }
    
    var res = Object.keys(data).reduce(function (obj, key, idx) {

      // Split the key into the property names
      var props = key.split('.');

      // If the accumulator object doesn't have a suitable property already,
      // create it
      if (!obj.hasOwnProperty(props[0])) {
        obj[props[0]] = {};
      }

      // Add the property and value
      obj[props[0]][props[1]] = data[key];

      // Return the accumulator object to keep collecting properties
      return obj;

    // Initialise with an empty object as the accumulator
    }, {});
    
    // Display the result
    document.write(JSON.stringify(res));