Manipulate JSON objects in AngularJS by deleting or adding items

This JSON is currently in my possession:

var videos = [
    {"id":"9854", "time": 56},
    {"id":"7859", "time": 29},
    {"id":"8745", "time": 59}
];

If an item is missing from the JSON, I want to add it, but if it's already there, I want to remove it.

Answer №1

When verifying the existence of an item, it is crucial to check its ID property.

The following function can help you achieve the desired outcome:

function manageItem(item) {
   var itemExists = false;
   for (var index = 0; index < itemList.length; index++) {
       if(item.id === itemList[index].id) { // If the item exists
           itemExists = true;
           itemList.splice(index, 1); // Remove from the list
           break;
       }
   }
   if(!itemExists) { // If the item does not exist, add it to the list
      itemList.push(item);
   }
}

Answer №2

First, you'll need to convert the object into a JavaScript object using JSON.parse(object). Once that's done, you can utilize if/else logic to determine if the desired field is present. If needed, you can then convert it back into JSON format with JSON.stringify(myObject).

There are multiple methods for checking the existence of a field. One option is to use if(myField === undefined), but depending on your requirements, you may need a more specific or robust approach. By researching this further, you should have all the information necessary.

Essentially, the task entails converting the JSON string into a usable JavaScript object and re-converting it back into a JSON string when required, especially for transmission purposes. If no JSON formatting is needed, you can keep it as an object for manipulation.

Another tip is to consider turning your array into an associative array with the ID number as the key. This allows for direct look-up without looping through the array every time. However, assess whether this modification is beneficial overall before implementing it solely for convenience.

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

creating styles for css elements using equations

I am curious about defining CSS element dimensions before they are rendered without using offset and jQuery. Is it possible to echo PHP into the width/height or position values? For example: <?php $width = 290px; $altwidth = 290; ?> <style> ...

Do you require API authentication for both the REST API and client running on the same server?

Let me give you an overview of the software we are working on: It's a web-based custom help desk application that requires users to log in using FOSUserBundle. Once logged in, they are directed to the dashboard where the frontend is built on AngularJS ...

Reading properties of undefined in React is not possible. The log method only functions on objects

I'm currently facing an issue while developing a weather website using the weatherapi. When I try to access properties deeper than the initial object of location, like the city name, it throws an error saying "cannot read properties of undefined." Int ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

angularslideables retro animation

I'm currently using the AngularSlideables library to toggle a modal within my Ionic project. You can check out a functional example in this fiddle: http://jsfiddle.net/3sVz8/19/ However, I am facing an issue where the initial height is set to 100% i ...

Tips for sending class objects with Typescript/React

I need to establish an Array of items with different characteristics as a Prop on my component. My goal is to transmit an array of items with unique properties to a component. Here's an example of what my array of objects might look like: ` let dish ...

Is it possible for jQuery UI Autocomplete to utilize values from various input fields simultaneously?

I've hit a roadblock with this code and it's been giving me trouble for some time now. Here is the current state of my auto-complete script: jQ19(function(){ // minLength:1 - how many characters user enters in order to start search jQ19 ...

AngularJS uses double curly braces, also known as Mustache notation, to display

I'm currently working on a project where I need to display an unordered list populated from a JSON endpoint. Although I am able to fetch the dictionary correctly from the endpoint, I seem to be facing issues with mustache notation as it's renderi ...

Is the MessageMap format used by Stomp beyond redemption?

When transferring MapMessages from Java to ActiveMQ and then using Stomp in PHP to retrieve them, I encounter an issue with the array structure. The Java message creation code is as follows: MapMessage message = session.createMapMessage(); message.setInt( ...

From converting JSON to Business Intelligence reports or tabular format

Currently, I am faced with a complex JSON structure that has 4 levels of hierarchy. I am in search of a reliable tool or solution that can help me convert this JSON object into a table format. So far, I have tried Power BI and other jQuery to table options ...

The TinyMCE editor's input box lost focus while on a popup dialog

Whenever I attempt to access the TinyMCE editor in a dialog box popup and click on "Insert link", the "Insert link" dialog box pops up but I can't type anything into the text field. I suspect that the issue may stem from having a dialog box open with ...

Encountered an error when attempting to extend the array function: Uncaught TypeError - Object [object Array] does not contain a 'max' method

Hello, I am currently attempting to integrate this function into my code: Array.getMaximum = function (array) { return Math.max.apply(Math, array); }; Array.getMinimum = function (array) { return Math.min.apply(Math, array); }; This is inspired ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

Best practices for timeout in HTTP long polling

As an avid user of Javascript AJAX and long-polling, I am constantly seeking the best value for server response timeout. Despite scouring numerous documents, a detailed explanation for timeout continues to elude me. Some suggest 20 seconds, while others ...

Deactivating Cluetip tool tips and adjusting the height limit in JQuery

How can I momentarily turn off the hints? I have seen references to being able to do so on the website and in this forum, but I am having trouble locating the command to disable them. I just need to temporarily deactivate them and then enable them again. ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

I must develop a custom function that generates a pure JavaScript string with the 'name' index and includes all the 'props'

My code is almost correct, but instead of returning a ':' in the Json result as desired, it returns a ','. Is there a way to achieve the desired result without modifying the JSON string like I did with the "replaces"? I am searching fo ...

THREE.js : Chart Your Course in the Digital Realm

When I have a moving object controlled by code such as: dx = [not important]; dy = [not important]; dz = [not important]; d = new THREE.Vector3(dx, dy, dz); mesh.postion.add(d); How can I ensure that my mesh is facing the direction it's moving in? I ...

In Node.js Express, the download window won't pop up unless the entire file has been sent in the header response

I have been using Express to develop an API that allows users to download PDF files. The download process is functioning correctly, but I am facing an issue where the download window, which prompts me to select a destination folder for the download, only a ...

Retrieve an item from an array based on the unique ID value of the button that was clicked using

I am working with a phones array that is populated with JSON data: var phones = [ { "age": 0, "id": "motorola-xoom-with-wi-fi", "imageUrl": "img/phones/motorola-xoom-w ...