在javascript中合并数组

时间:2016-04-03 20:46:05

标签: arrays

我有这个数组:

datas = [{USR_Website: "http://domain.com"}, {USR_FirstName: "Alex", USR_LastName: "Black", USR_Email: "ab@domain.com"}, {USR_Password: "fc6e6d7c3a72b46a69e2f8f594a775acef6b3ba1"}, {USR_Country: "CA", USR_TimeZone: "America/New_York"}];

如何将此数组转换为:

datas = {USR_Website: "http://domain.com", USR_FirstName: "Alex", USR_LastName: "Black", USR_Email: "ab@domain.com", USR_Password: "fc6e6d7c3a72b46a69e2f8f594a775acef6b3ba1", USR_Country: "CA", USR_TimeZone: "America/New_York"};

我希望这样,因为datas.USR_Emaildatas[1].USR_Email更容易   public void AddChildStructureLevel(Structure childStructureLevel) { try { TryPassNameValidation(childStructureLevel.Name); // throws if something is wrong Children.Add(childStructureLevel); } catch (ArgumentException ae) { throw new ArgumentException($"Provided structure name {childStructureLevel.Name} is invalid.", ae); } Trace.WriteLine($"Added new child structure level to parent structure children."); } private void TryPassNameValidation(string structureName) { TryPassingStructureNameMinMaxLength(structureName); TryPassingStructureNameUnique(structureName); } private void TryPassingStructureNameMinMaxLength(string structureName) { bool nameIsTooLong = structureName.Length >= maxLengthStructureName; bool nameIsTooShort = structureName.Length <= minLengthStructureName; if (nameIsTooLong) throw new ArgumentException($"Structure name is too long. Max {maxLengthStructureName} characters."); if (nameIsTooShort) throw new ArgumentException($"Structure name is too short. Min {minLengthStructureName} characters."); } private void TryPassingStructureNameUnique(string childName) { foreach (Structure child in Children) //TODO: recurse over children.children if (child.Name == childName) throw new ArgumentException($"Structure level name {childName} already exists."); }

或许,另一种解决方案?

感谢。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

var target = {};
for (var i = 0, l = datas.length; i < l; i++) {
    for (var key in datas[i]) {
        target[key] = datas[i][key];
    }
}

您现在可以将数据作为target的属性进行访问,例如。 target.USR_Country