How to include a key-value pair to a JSON object within an array using JavaScript

I am looking to include the following functionality in the JSON data provided below: "Check if the key name default exists, and if it does, add another key within the same object => ("pin" : 91)." I have attempted to achieve this using the code snippet below.

var myObj = {
     "data": [{
         "code": "EN",
         "language": "English",
         "content_available": true,
         "isdefault": true
     }, {
         "code": "AR",
         "language": "Arabic",
         "content_available": true,
         "isdefault": false,
                "default" : true

     }, {
         "code": "BR",
         "language": "Brazilian Portuguese",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "CN",
         "language": "Simplified Chinese",
         "content_available": true,
         "isdefault": false,
                "default" : true
     }, {
         "code": "TW",
         "language": "Traditional Chinese",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "DE",
         "language": "German",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "ES",
         "language": "Spanish",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "FR",
         "language": "French",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "JP",
         "language": "Japanese",
         "content_available": true,
         "isdefault": false,
                 "default" : true
     }, {
         "code": "RU",
         "language": "Russian",
         "content_available": false,
         "isdefault": false
     }],
     "success": true
 }
function addKey(k) {
  for (var key in myObj.data) {
    if (myObj["data"][key] === k) {
      myObj["data"][key]["pin"] = "91";
    }
  }
}
addKey("default");
console.log(myObj);

Answer №1

To ensure you have all the necessary keys in your object, simply loop through the key names and create them if they do not already exist. Remember to consider the data types involved - use for/in for objects and forEach() for arrays.

var myObj = {
     "data": [{
         "code": "EN",
         "language": "English",
         "content_available": true,
         "isdefault": true
     }, {
         "code": "AR",
         "language": "Arabic",
         "content_available": true,
         "isdefault": false,
                "default" : true

     }, {
         "code": "BR",
         "language": "Brazilian Portuguese",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "CN",
         "language": "Simplified Chinese",
         "content_available": true,
         "isdefault": false,
                "default" : true
     }, {
         "code": "TW",
         "language": "Traditional Chinese",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "DE",
         "language": "German",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "ES",
         "language": "Spanish",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "FR",
         "language": "French",
         "content_available": true,
         "isdefault": false
     }, {
         "code": "JP",
         "language": "Japanese",
         "content_available": true,
         "isdefault": false,
                 "default" : true
     }, {
         "code": "RU",
         "language": "Russian",
         "content_available": false,
         "isdefault": false
     }],
     "success": true
}

 
function addKey(k) {

  // Use forEach() on arrays instead of for/in loops
  myObj.data.forEach(function(obj){
    
    // Loop through each object in the array using for/in
    for(var prop in obj){
      // Check if the current property matches the provided key argument ("default")
      if(prop === k){
         // Add a new key/value pair to the object
         obj["pin"] = "91";
      } 
    }
  });
}
addKey("default");
console.log(myObj);

Answer №2

function verifyKey(obj, key) {
    for (var x = 0; x < obj.data.length; x++) {
        if (obj.hasOwnProperty(obj.data[x]) && obj.data[x][key] !== undefined) {
            obj.data[x].pin = 91;
        }
    }
}

verifyKey(myObject, 'default');

To start, we extract the data key from the object. As it's in an array format, we loop through each element. Next, we confirm whether the default key holds a defined value or not before assigning the pin key only if a value has been specified.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

Implementing new Datatables 1.10 parameters for model binding

There have been changes in the ajax server side parameters for Datatables 1.10. The previous model looked like: public class DataTableParamModel { public string sEcho{ get; set; } public string sSearch{ get; set; } public int iDisplayLength{ ...

Utilizing AngularJS: Using ng-click with ng-repeat to retrieve all data simultaneously

Having a simple ng-repeat: <div ng-repeat="x in names"> <h4>{{x.productid}}</h4> <h4>{{x.newquantity}}</h4> <h4>{{x.total}}</h4> <button ng-click="addInfoAboutOrder(x)">Add Info</button> ...

The AnimationMixer is refusing to start playing the animation from the gltf file

I have successfully imported a model using three.js and it works fine. Now, I am trying to run animations from a GLB file. Although I can retrieve the animation names with three.js, the TJS library fails to play my animations. GLB FILE There are two anim ...

Enhance your SQL FOR JSON query by including an additional array bracket

I've been on a long search for an answer to this question: How can I add an additional array bracket in the subselect? Here is the Query I have: select -- Images ( SELECT tMedien.WebshopID AS 'mediaId', ...

Unable to establish a connection to the server while handling a jQuery Ajax error

I'm in the process of pinpointing an issue that occurs when submitting an Ajax request through jQuery and encountering a failed connection to the server. The scenario involves loading a page from the server, then deliberately disconnecting the network ...

In a Next.js project, Typescript seems to be overlooking errors related to proptype definitions and function types

Greetings everyone! I am currently working on a project using TypeScript and have implemented various rules and elements. However, I am facing issues with type errors for functions and props. Essentially, when using any function, it is necessary to specify ...

ReactJS is unable to identify a specific value within an array object

Currently working on a web app using express + react where JSON data is being sent. Utilizing axios to fetch the data and setState to assign the messages variable to response.data.messages { "messages":{ "message":{ "us ...

Remove a div using JavaScript

My approach involves dynamically adding div elements using JavaScript in the following manner: <div id="detail[0]"> <input name="detail.Index" type="hidden" value="0" /> <input name="detail[0].details_name" type="text" /> ...

Removing an element with a specific class that was created with Javascript can be done by clicking outside the box

I needed to eliminate an element that was created using JavaScript of a specific class when clicked outside the box. I have created a color-picker using .createElement and added a class to it. Now, my goal is to remove that picker whenever a click occu ...

Changing the URI in accordance with the previous URI

I am encountering an issue in my React application where multiple updates of the URI are being made within the same event by adding query parameters using the router.push function from various locations in the code. However, some updates are getting lost b ...

How to retrieve data from an undefined table using Sequelize that is created through association

I've encountered a new challenge while working on my latest project; Imagine the tables User and Project in Sequelize have been defined. There's also a third table in the database called ProjectsUsers, and I need to retrieve data from there. T ...

c# selecting a specific token using jtoken

I'm having some trouble extracting a URL value from a JSON using JSON.net and the jtoken SelectTokens method. I can successfully retrieve the label for the URL, but I can't seem to access the actual URL value. Specifically, I am trying to extrac ...

Using sinon.js version 1.10, jQuery version 2.1, and making synchronous requests

I have been attempting to simulate a server using sinon.js and calling it with jQuery.ajax, but I am facing issues getting it to work. Here is the code snippet: $(function() { var server = sinon.fakeServer.create(); server.respondWith('POST&apo ...

Tips for incorporating an outside model into vue.js with babylon js

Struggling with importing a gltf file into vue.js using babylon.js to create a 3D view on a webpage. The documentation online isn't very clear, and I've tried the following steps in my Hello.vue file: <div> <h1> Hello </h1> < ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...

Recover files from the latest commit in Git, with files having no data inside them

Hello there! I encountered an issue with Git recently. I was attempting to clone a repository in order to push my project code, but I ran into an upstream error. I tried doing a git pull without success, then attempted to revert back to my initial commit ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...

Enhancing MEAN Stack Application by Updating Table Post Database Collection Modification

In my efforts to ensure that my table data remains synchronized with the database information, I have encountered an issue. Whenever Data Changes: $scope.changeStatus = function($event,label,status){ var target = $event.currentTarget; target ...

Tips for Waiting for Binding in an Angular 1.5 Component (No Need for $scope.$watch)

Currently, I am in the process of developing an Angular 1.5 directive and have encountered a frustrating issue related to manipulating data that is not yet available. Below is a snippet of my code: app.component('formSelector', { bindings: { ...