How to dynamically insert a key into an array by locating a specific value in AngularJS

I need help adding a new key to a JSON array by searching for a specific key value.

For example JSON:-

[
  {
    "$id": "2025",
    "ID": 41,
    "Name": "APPLE"
  },
  {
    "$id": "2026",
    "ID": 45,
    "Name": "MANGO"
  },
  {
    "$id": "2027",
    "ID": 48,
    "Name": "GUAVA"
  }
]

Let's say I want to add a new key pair like "Price": 50 after "Name": "MANGO" or by finding the ID ID: 45. The expected updated JSON should look like this:

[
  {
    "$id": "2025",
    "ID": 41,
    "Name": "APPLE"
  },
  {
    "$id": "2026",
    "ID": 45,
    "Name": "MANGO",
    "Price": 50
  },
  {
    "$id": "2027",
    "ID": 48,
    "Name": "GUAVA"
  }
]

The new key-value pair should be added to the object related to the matched search key.

I'm having trouble finding a function that addresses this issue. Can anyone provide guidance?

Answer №1

If you want to dynamically add a property to an object based on certain conditions, you can achieve this by running a loop and checking the condition before adding the property. Check out the code snippet below for an example:

var myarray = [
                {
                    "$id": "2025",
                    "ID": 41,
                    "Name": "APPLE"
                },
                {
                    "$id": "2026",
                    "ID": 45,
                    "Name": "MANGO"
                },
               {
                   "$id": "2027",
                  "ID": 48,
                   "Name": "GUAVA"     
                        }
]
for(var i=0;i<myarray.length;i++){
   if(myarray[i].$id === "2025" || myarray[i].Name === "APPLE"){
        var data = myarray[i];
        data.price = 50
      }
}
console.log(myarray)

Answer №2

One way to add the Price key to an object is by using the array#find method to compare the ID.

let arr = [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", "ID": 48, "Name": "GUAVA" } ],
    id = 45,
    obj = arr.find(({ID}) => ID === id);
if(obj);
  obj.Price = 50;
console.log(arr);

Answer №3

If you want to update the price of an item with ID 45, you can use this code:

data.find(item => item.ID === 45).price = 50;

In case the item is not found in the data array, you can handle it by using this code:

(data.find(item => item.ID === 45) || {}).price = 50;   

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

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...

Identify whether the final digit falls within the range of 1-4 or 5-9, and then apply styling to the corresponding

First, this is the structure of my table: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <table class="table group-9569" width="100%"> <tbody> <tr> <td class=" ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

Looking to arrange an array group based on a particular key value in PHP?

I require assistance with organizing an array that contains different groups with the same value for each group. I am looking to sort the groups in descending order. Please see the example below: Array ( [0] => Array ( [0] => ...

Deciphering JSON in Golang to form a slice containing a string and a float64 value

I'm currently working on querying a database that is located on a server. The issue arises when I attempt to decode the JSON data into a 2D slice, as one element is a string while the other is a float64. To tackle this problem, I initially tried modi ...

Issue: Unhandled ReferenceError - onChangeAssignedGroup function is not declared within scope at HTMLSelectElement.onchange

Having difficulty calling a PHP script via JavaScript when the user changes the value in the "Assigned To Group" selection. The goal is to modify the option list of a yet-to-be-created "Assign to User" selection. An error message pops up stating that it d ...

Utilize the JSON response upon successful completion of an AJAX request

I'm currently working with this code snippet: function openIzmeni(value) { $.ajax({ url: "getRzaizmenu.php", type: "POST", async: true, data: { vrednostid:value}, //your form data to post goes here as ...

Error message encountered while trying to instantiate 'FormData'

My contact form was working perfectly fine until recently when it suddenly stopped allowing me to send messages. I keep encountering this error message every time I try to submit the form: Uncaught TypeError: Failed to construct 'FormData': pa ...

Leveraging variables with jQuery within a Django template filter

My goal is to fetch data using Jquery, followed by the application of a Django template filter. The template itself is powered by jinja2. When dealing with a click event, I have the following code: $('#get_name').click(function(event){ var ...

Dynamic elements in ViewModel

Looking to parse the following JSON in .NET "currentData": { "Name": {"system": "wfdss", "canWrite": true }, "DiscoveryDateTime": { "system": "wfdss", "canWrite": true }, "Code": { "system": "code", "canWrite": false }, ... } Since these el ...

What is the best way to leverage an existing user database and integrate user authentication into a fresh project?

I have recently taken on the task of revamping an established project by creating a brand new frontend from scratch. After careful consideration, I have opted to develop a straightforward Vue/Node.JS project. Within the current framework lies a Postgres d ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

Screen content of a post request in Node.js

Can this code in node.js + express be simplified? // Code snippet for registering a new participant app.post('/api/participant', function (req, res, next) { var data = req.body; // Ensure only specific fields are uploaded var parti ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

Obtain a collection of custom objects through an HTTP GET request to be utilized in an Angular 2 application

I am currently grappling with the task of efficiently retrieving a list of custom objects and displaying their contents using an HTML file. Here is a simplified version of the HTTP GET method that I am working with: [HttpGet("/atr/testing")] public List& ...

Experiencing difficulties with arrays in JavaScript while using React Native

Programming Challenge let allURL = [] const [toReadURL, setToReadURL] = useState([]) useEffect(() => { const listReference = sReference(storage, parameterKey) // Retrieve all the prefixes and items. listAll(listReference) .then((res ...

The length of JSON data retrieved may vary between Internet Explorer and Firefox

After receiving JSON data from the server via AJAX, I proceeded to evaluate it as follows: request.responseText=[{name:xxx},{name:yyy},{name:zzz}]. I then used the following code snippet: var data=eval(request.responseText); alert(data.length); Surpri ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

Fetching byte array from Spring Boot and transmitting it to Vue frontend

I am faced with a challenge involving functions that require reading an encoded image string from my MongoDB database, decoding it, and sending it to my Vue frontend for downloading. @GetMapping(path = "/signature/{signatureId}", produces = MediaType.IMAG ...