Insert an item into a JSON array based on its name or value

I've been able to successfully remove items from a JSON array, but I'm struggling with adding new items. Here's the current array:

var users = [ 
        {name: 'james', id: '1'}
    ]
    

I want to add an item so the array looks like this:

var users = [ 
        {name: 'james', id: '1'},
        {name: 'thomas', id: '2'}
    ]
    

The code for removing an item from the array is as follows:


        Array.prototype.removeValue = function(name, value){
            var array = $.map(this, function(v,i){
                return v[name] === value ? null : v;
            });
            this.length = 0; //clear original array
            this.push.apply(this, array); //push all elements except the one we want to delete
        }; 

        removeValue('name', value);
    

What modifications do I need to make in order to add values to the array instead?

Answer №1

How can you use Array.prototype.push()?

var activities = ["hiking", "swimming"];
var count = activities.push("yoga", "running");

console.log(activities); // ["hiking", "swimming", "yoga", "running"]
console.log(count);  // 4

Answer №2

In my opinion, the filter function seems more appropriate than map.

 Array.prototype.removeValue = function(name, value){
    var array = $.filter(this, function(v,i){
       return v[name] !== value;
    });
    this.length = 0; //clear original array
    this.push.apply(this, array); //push all elements except the one we want to delete
 }

I can't say for sure if the length and push methods will work as intended, as I have not personally tested them myself.

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

Tips for correctly parsing data into my Retrofit client for a successful post request

Struggling to send JSON via a POST request to a REST API using Retrofit. The issue lies in figuring out the data type (JSONArray, String, INT...etc) that Retrofit requires for the POST operation. I've attempted to hard code the JSON as a string and pa ...

How can you ensure that double quotes are interpreted as literals in replacement when using xargs?

My source file contains JSON-Objects separated by lines, like this: Here is the source: {"_id":"1","name":"one"} {"_id":"2","name":"two"} {"_id":"3","name":"three"} I need to send each line to a curl -X POST -H "application/json" myURL -d '<REP ...

After a setTimeout is called, the string in Ionic/Angular 2 does not update as expected

Hey there! I've been trying to update a string linked to a specific class or tag using settimeout or another callback, but unfortunately, I haven't had any success. It seems to work perfectly fine when triggered by a button click, but for some re ...

Focusing on a specific image using Jquery

I am looking to specifically target the image within the "hero1project3" class, however, the image is currently set as a background. Is there a way in jQuery to apply effects like blur only to the image itself, for example, using ".hero1project3 img"? HTM ...

Combining tables utilizing a JSONB column value in postgresql

I am working with two tables in postgresql. The first table (product) contains a JSON row for sku ([149461190]) The second table (item) has a regular sku column How can I successfully join these tables on the sku? I attempted the following approach, whic ...

A guide on extracting keywords from the tynt API using JavaScript

Looking to extract the inbound keyword from an API: What would be the best way to use JavaScript to extract and display the value of the inbound keyword from this API? ...

Is there any event triggered when the src attribute of an image is modified?

I am currently working on a project where I am dealing with images of different sizes, and my goal is to adjust the parent div size based on the height of the new image. Within my code, I have set inner, viewOne, and viewTwo as global variables. Here is a ...

Is it possible to send keystrokes using ajax after a 1-second delay?

I am looking for a way to send keystrokes typed in a text field at one-second intervals. This approach aims to reduce the burden of sending an ajax request with every keypress. For example, if the user types 4 letters within a second, the request will con ...

Struggling to grasp the concept of DOM Event Listeners

Hello, I have a question regarding some JavaScript code that I am struggling with. function login() { var lgin = document.getElementById("logIn"); lgin.style.display = "block"; lgin.style.position = "fixed"; lgin.style.width = "100%"; ...

Stopping a Firefox addon with a button click: A step-by-step guide

Utilizing both the selection API and clipboard API, I have implemented a feature in my addon where data selected by the user is copied to the clipboard directly when a button is clicked (triggering the handleClick function). However, an issue arises when a ...

Retrieving CSS properties of an element using JavaScript

How can I efficiently retrieve all CSS rules associated with a specific element using JavaScript? I am not seeking a particular solution, just looking to capture all CSS rules for the given element. For example, consider the following HTML code: <div ...

Is it possible to showcase the $timeout duration using a progress bar?

I'm considering showcasing the remaining time using my $timeout to notify individuals when their time is finished. Unfortunately, I haven't been able to locate any information about this online. Therefore, my query is... Is it feasible to displ ...

What is the best method to transfer information from a What You See Is What You Get editor to a database using Vue.js?

I have recently started using the Vue2Editor in order to streamline my process of sending text and image data to my Firebase database. However, I am encountering an issue where the entered data is not being added successfully. Previously, with traditional ...

Using jQuery to locate the dimensions of an image and then adjusting the height and width of a div using

I'm currently working on a project where I need jQuery to determine the size of each image (approximately 8-10 images per page) within an Owl Carousel. However, every time I check in the developer tools, all I see is width: 0px, height: 0px Here&apos ...

I'm so confused about the operation of each method in this context

I am experimenting with a simple process involving setTimeout function. My goal is to make the letters of a name appear individually and gradually at different times. For example, if the name is NAZ, I want the letters to appear in this order: first N, the ...

Leveraging xgettext for extracting translatable content from VueJS files

Attempting to utilize xgettext for extracting translatable strings from a VueJS file has presented some challenges. Specifically, xgettext does not seem to recognize JavaScript code within a computed property in VueJS. For instance, consider the following ...

Challenges with nesting radio button groups in jQuery validation

Trying to implement a custom validation method for a group of radio buttons in v1.9 of the jQuery validate plugin. Despite this article, it is indeed feasible to have radio buttons with the same name attribute, as long as different class rules are applied ...

The submission of an Angular form results in errors such as being unavailable or

After building a registration page component in Angular and following tutorials, I encountered a frustrating bug. When pressing the submit button on the form, the console would display "undefined" when attempting to access the NgForm's value. However, ...

Refactor these codes by utilizing a single loop in React

Can you help me with reducing the amount of code in this function? The code provided below is functional and does not have any issues. flag : boolean, likeArr: ["A", "B", "C"], dislikeArr: ["D", "E", "F"] likeOrDislike( flag, likeArr, dislikeArr ) { ...

Implementing a callback in the app.get function within Node.js: A step-by-step guide

I have a fully functioning website and now I am looking to add some logic and data analysis to it. Below is the code snippet for rendering my /data page: app.get("/data", (req, res) => { const sql = "SELECT * FROM MyMoods"; cons ...