简体   繁体   中英

Transforming JavaScript Array into Object

I have a strange requirement to transpose or transform a valid javascript array into another javascript object.

I am getting a server response in this format

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

I would like this array to be changed to this format.

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

Still struggling in JavaScript and after hours of searching and trying, I have been unsuccessful. Your help is greatly appreciated.

Just use the operator [...] to get an object property.

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"]
  }
};

What you have is an object, not an array.

You can use Object.keys to get an array of the own property names of the object, then iterate over that using reduce to create the new object. The code below should be sufficiently commented, ask questions if not.

  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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM