Categories
JavaScript Answers

How to add a new key value pair in existing JSON object using JavaScript?

Spread the love

Sometimes, we want to add a new key value pair in existing JSON object using JavaScript.

In this article, we’ll look at how to add a new key value pair in existing JSON object using JavaScript.

How to add a new key value pair in existing JSON object using JavaScript?

To add a new key value pair in existing JSON object using JavaScript, we can parse the JSON string with JSON.parse, then add the key-value pairs we want, and then convert the object back to a JSON string with JSON.stringify.

For instance, we write:

const s = `{
  "workbookInformation": {
    "version": "9.1",
    "source-platform": "win"
  },
  "datasources1": {

  },
  "datasources2": {

  }
}`
const obj = JSON.parse(s)
obj.foo = 'bar'
const newS = JSON.stringify(obj)
console.log(newS)

to parse s into an object with JSON.parse.

Then add the foo property to obj.

And then we call JSON.stringify with obj to convert it back to a JSON string.

Therefore, newS is {"workbookInformation":{"version":"9.1","source-platform":"win"},"datasources1":{},"datasources2":{},"foo":"bar"}.

Conclusion

To add a new key value pair in existing JSON object using JavaScript, we can parse the JSON string with JSON.parse, then add the key-value pairs we want, and then convert the object back to a JSON string with JSON.stringify.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *