0

I have the following JavaScript object which prints the following JSON using

var str = JSON.stringify(finalNodesData, null, 2);
console.log(str);

Printed JSON

[
  {
    "jobDate": "2023-01-03 13:48:29.402",
    "id": "b186c313-a2f3-44a8-9803-066c6d52e8a0"
  },
  {
    "jobDate": "2023-01-03 13:57:19.988",
    "id": "db182f5e-9622-42e9-bbe8-19bee4d878d4"
  }
]

How can I add two new elements "submitedBy" and "submitReason" to the JSON? I want my JSON to look like

{
    "submitedBy": "Bob Smith",
    "submitReason": "Because of an error",
    "nodeData": [
      {
        "jobDate": "2023-01-03 13:48:29.402",
        "id": "b186c313-a2f3-44a8-9803-066c6d52e8a0"
      },
      {
        "jobDate": "2023-01-03 13:57:19.988",
        "id": "db182f5e-9622-42e9-bbe8-19bee4d878d4"
      }
    ]
}

I want to use JavaScript variables to generate the JSON, and not concatenate strings.

1
  • 2
    you add it before you create a json, or use JSON.parse to convert it back to object, add new items and then convert back to string. Commented Jan 4, 2023 at 11:42

2 Answers 2

1

Note: Your new JSON is no longer an Array, but an Object.

finalNodesData = {};  
finalNodesData["nodeData"] = nodeData; // this is your old data
finalNodesData["submitedBy"] = "Bob Smith";
finalNodesData["submitReason"] = "Because of an error";

var str = JSON.stringify(finalNodesData, null, 2);
console.log(str);
Sign up to request clarification or add additional context in comments.

Comments

0

The best way of doing this is adding the data to the JavaScript object before converting it to JSON.

let finalNodesData = [
  {
    jobDate: "2023-01-03 13:48:29.402",
    id: "b186c313-a2f3-44a8-9803-066c6d52e8a0"
  },
  {
    jobDate: "2023-01-03 13:57:19.988",
    id: "db182f5e-9622-42e9-bbe8-19bee4d878d4"
  }
]


const submittedBy = "Bob Smith"
const submitReason = "Because of an error"

finalNodesData = {
  submittedBy,
  submitReason,
  nodeData: finalNodesData
}

var str = JSON.stringify(finalNodesData, null, 2);


console.log(str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.