JS_basic_knowledge
JS_basic_knowledge

Reputation: 117

Creating new object from 2 existing objects

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

Upvotes: 2

Views: 1002

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

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

Upvotes: 0

testing_22
testing_22

Reputation: 2585

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)

Upvotes: 5

Related Questions