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

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Troubleshooting SProckets Error During Rails App Deployment on Heroku

I am having trouble deploying a Ruby on Rails app on Heroku and encountering errors during the push process. When I run the console command git push heroku master While it is installing dependencies, I receive the following error. Sprockets::FileNot ...

What are some ways to detect if JavaScript is enabled on the client side?

In the process of creating a web application, I have structured my code to dynamically generate JavaScript functions using PHP. However, it has come to my attention that if JavaScript is disabled on the client side, my application will not function as in ...

JavaScript function to toggle visibility and scroll back to top of the page

I have been an avid reader on this platform, and I am hoping that my question has not already been addressed. I am struggling to find a solution to a problem I am facing. There are two DIVs in my code that I toggle between showing and hiding using Javascr ...

Turning an array into JSON using PHP

I'm encountering some difficulty in parsing the data as I attempt to change the shape of the array into JSON format. Here is an example of the current array structure: Array ( [id] => 1 [fisrt_name] => raul [last_name] => gon ...

The onclick event in JavaScript is unresponsive on mobile devices

Our website is powered by Opencart 1.5.6.4 and the code snippet below is used to add items to the shopping cart. <input type="button" value="<?php echo $button_cart; ?>" onclick="addToCart('<?php echo $product['product_id']; ?&g ...

Extracting HTML elements between tags in Node.js is a common task faced

Imagine a scenario where I have a website with the following structured HTML source code: <html> <head> .... <table id="xxx"> <tr> .. </table> I have managed to remove all the HTML tags using a library. Can you suggest w ...

Ways to avoid browser refresh when uploading files in React applications

I'm working with a simple file upload form in React using hooks. import React, { useState } from 'react'; import { FlexContainer } from '@styles/FlexContainer'; const TestUpload = () => { const [file, setFile] = useState<F ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

Unable to resize images in Firefox

Why is it that resizing doesn't seem to work in Firefox but functions fine in Internet Explorer? I'm struggling to find a way to make it consistent across all browsers. My goal is to resize the width to 800 and height to 475, disable maximizing t ...

Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page. Here is the c ...

What is the best way to verify and eliminate unnecessary attributes from a JSON request payload in a node.js application?

My goal is to verify the data in the request payload and eliminate any unknown attributes. Example of a request payload: { "firstname":"john", "lastname":"clinton", "age": 32 } Required attributes: firstname and lastname Optional a ...

Angular 6 component experiencing issues with animation functionality

I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService, there's an array that holds ...

The Django CSRF token is inaccessible for retrieval

I'm in the process of developing a website using Vue.js for the frontend and Django for the backend. I've made sure to include the csrf token in every request from the frontend to the backend to prevent any 403 Forbidden errors. All requests are ...

Display hidden text upon clicking using React Material UI Typography

I have a situation where I need to display text in Typography rows, but if the text is too long to fit into 2 rows, ellipsis are displayed at the end. However, I would like to show the full text when the user clicks on the element. I am attempting to chang ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this? Below is my component setup: <template> <div> <v-server-table :columns="columns" url="/object/find" :options="option ...

Prevent user input in box until anchor link is activated

To implement the functionality of disabling the input text box until a username is clicked, I have attempted to use the ng-disabled, but so far it has not been successful. It seems like setting a model for the usernames in the users list to check their st ...