Creating new object from 2 existing objects

Viewed 167

I have the following:

var identificationIDs = [
{
    "HolderID": "1A000714",
    "TempIssueID": "1A000700"
}
]

Which I am trying to update to include a new object "ExtendedID" with some values to look like below:

var identificationIDs = [
{
    "HolderID": "1A000714",
    "TempIssueID": "1A000700",
    "ExtendedID": [
      "1A000714",      
      "1A000700"
    ]
}
]

Running into issues with trying to push HolderID and TempIssueID into the new object.

Here is my code:

// Simplify variable name:
var userID = identificationIDs;

// Create new object and assign values:
for (var i = 0; i < userID.length; i++) {
   
    userID[i].HolderID = userID[i].ID;
    userID[i].ExtendedID = userID[i].HolderID.push(TempIssueID);
}

console.log(userID);
2 Answers

You can use Javascript's built-in spread syntax to help you out.

If you're playing around with arrays, minor changes should be made. Take a look at an example:

let identificationIDs = {
    "HolderID": "1A000714",
    "TempIssueID": "1A000700"
}

let extendedId = [
      "1A000714",      
      "1A000700"
    ]


let newIdentificationIds = {...identificationIDs, ExtendedID: extendedId};
console.log(newIdentificationIds)

You can try these following ways.

var identificationIDs = [
  {
    HolderID: "1A000714",
    TempIssueID: "1A000700",
  },
];

// Using `Object.values`
const result = identificationIDs.map((obj) => ({
  ...obj,
  ExtendedID: Object.values(obj),
}));

// Alternatively, use destructuring
const result2 = identificationIDs.map(({ HolderID, TempIssueID }) => ({
  HolderID,
  TempIssueID,
  ExtendedID: [HolderID, TempIssueID],
}));

console.log(result);
console.log(result2);

Related