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

I'm receiving /generate_seeker/?complete_list=true, but what I actually need is /generate_seeker?complete_list=true

Check out this code snippet that utilizes axios in a React project. axios.get(`https://resolab-backend.herokuapp.com/core/create_seeker`,{ params:{ complete_list : true }, headers:{ 'Authorization': `Token ${cookies.get("token")}` } ...

Incorporate additional plugins into React-Leaflet for enhanced functionality

I'm currently working on developing a custom component using react-leaflet v2, where I aim to extend a leaflet plugin known as EdgeMarker. Unfortunately, the documentation provided lacks sufficient details on how to accomplish this task. In response, ...

existing event handler in JavaScript has already been registered on a particular plugin

Apologies for the confusing title, will make changes accordingly.. Currently, I am utilizing the Twitter Bootstrap Wizard to manage database operations. My goal is to find a way to activate the onTabShow() function by simply clicking a button. The onTabSh ...

Unraveling the mysteries of JQuery AJAX POST and Serialization techniques!

I am struggling to implement an AJAX request using JQuery to validate and submit a form, extract its values, and assign them to variables for further use. Unfortunately, I lack a clear understanding of AJAX functionality as well as how serializing works. ...

How to Populate Object Literal with Multiple Objects in AngularJS

When I click on "Evan", I receive the following response: {"id":1,"name":"Evan"} If I click on "Robert", I will get: {"id":2,"name":"Robert"} Is there a way to modify this code so that it follows the aforementioned steps and generates an object similar ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Error encountered in Express.js blogging app: Issue arises when attempting to filter posts by category, resulting in a "Cast to ObjectId failed" error

Currently, I am developing a blogging application using technologies like Express, EJS, and MongoDB. In the application, I have structured posts into different categories, each stored in its own collection. However, I encountered an issue while attemptin ...

Obtaining JSON data with CURL

Greetings, I recently started learning about the foursquare API but have hit a roadblock when trying to obtain an Access Token. Below is a snippet of code I found on Stack Overflow: // build url $url = 'https://foursquare.com/oauth2/access_token&apos ...

reasons why the keypress event may not be triggered

Hello there, I am trying to create a function that simulates pressing the 'tab' key. The function is supposed to restrict input within specific ranges and return the cursor to another range once the limit is reached. Additionally, if a user input ...

Guide to saving an Object to a file (JSON) within the project directory using React Native for Debuggingpurposes

Feeling a bit overwhelmed trying to tackle this issue. My goal is to save data to a JSON file in real-time while debugging my application. I have a Redux store state that I want to organize neatly in a file for easier debugging, so exporting/writing the ob ...

The error message states that the element (0 , _dayjs.Dayjs) is not a valid function

I am currently in the process of replacing momentjs with dayjs. To start, I included the necessary dependencies: "dayjs":"1.10.7" Next, I imported dayjs like this: import { Dayjs } from 'dayjs'; To retrieve the start of the ...

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

Why is it necessary to use 'this.' to reference a function inside a Component in React?

class First extends React.Component{ handleClick(){ alert('handle click'); } render(){ return <div> <button onClick={this.handleClick}>click</button> </div>; } } Explo ...

Utilizing JSON and Jackson libraries to map JSON data back to Plain Old Java Objects (PO

Currently, I have a JSON string that I want to convert into a POJO: { "fruit": { "weight":"29.01", "texture":null }, "status":"ok" } To achieve this mapping, I am using the Jackson JSON object/JSON mapping framework along with ...

Error: Attempting to access a property 'notesObjectInService' that is undefined on the object

I'm currently facing an issue where my controller is unable to load an object from a service called notesFactory. The console.log(typeof notesFactory) statement returns 'undefined', causing notesObjectInService to trigger an exception. Desp ...

Exploring the power of data-callbacks in VueJS

For instance, if we have <div data-callback="recaptchaCallback"></div>, the recaptchaCallback function will run as shown: <script> function recaptchaCallback() { alert('OK'); } </script> The code above functions prop ...

Ways to manage multiple Observables

Two Observables are being returned from different services, each providing only one value (similar to Observable.just()). In TypeScript, types play a crucial role in this context. Is there a method to determine when both Observables have been resolved (in ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...

Can values be retrieved or updated from a vector<json> using a pointer?

Currently in the midst of exploring C++, my focus is on finding the most recurring values in a large array using vectors and json. To enhance efficiency, I opted to introduce threading but encountered issues with pointers and addresses. The task at hand i ...

Importing models in SceneJS does not function properly with Internet Explorer

I've been exploring different webGL frameworks lately. While I like SceneJS, I've noticed some compatibility issues with Internet Explorer. For instance, in IE 11, importing OBJ files seems to cause the online examples to freeze up: Check out th ...