Ad

Convert Object A To Match Format Of Object B And Merge Them JavaScript

- 1 answer

I got two data structures in different formats.

The first:

{loginRememberMe: false, test: false}

The second:

[
  {
    Objectname: "loginEmail",
    value: "one"
  },
  {
    Objectname: "loginPassword",
    value: "two"
  }
]

I am trying to convert the first structure to match the format of the second structure and to then merge them.

This needs to be done using JavaScript / jQuery,

Ad

Answer

In future please show the final structure you need to have. You cannot directly merge an Object with an Array.

var first = {
  loginRememberMe: false,
  test: false
}

var second = [{
  Objectname: "loginEmail",
  value: "one"
}, {
  Objectname: "loginPassword",
  value: "two"
}]

var modifiedArray = addObjectKeysToArray(second, first);

console.log( modifiedArray );
console.log( second );
console.assert(second !== modifiedArray, 'both arrays should be different');

function addObjectKeysToArray(arr, obj) {
  // copy the arr so we don't modify the original
  var arrCopy = arr.slice(0);
  // loop through the object properties
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      // add to the copied array
      arrCopy.push({
        Objectname: key,
        value: obj[key]
      });
    }
  }
  return arrCopy;
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

Ad
source: stackoverflow.com
Ad