Remove an element from a mapping of type <String,String> in Javascript

Question! How can I remove a specific element from this JavaScript object by its ID?

[  
   "{\"id\":\"b00a3a47-783a-4af5-90d9-59c4deb7a9e3\",\"notes\":\"sdfsdf\",\"recordType\":0}",
   "{\"id\":\"a6f72972-502e-452b-9773-51699a527122\",\"notes\":\"sdfsfdf\",\"recordType\":0}"
]

I attempted the following code snippet:

var index = detailsArray.map(function (element) {
                    console.log("element = " + JSON.stringify(element) + " index = " + index + " id = " + element.id);
                    return element.id;
                }).indexOf(detailId);
                console.log("index of " + detailId + " = " + index);
                delete detailsArray[index];

However, I encountered an issue where element.id was returned as undefined. I suspect this is due to the properties of the element being in string format. Any suggestions on how to fix this?

Answer №1

The collection consists of an array of JSON strings.
To conduct a filtering process, one must decode each element and verify the id for equivalence:

var jsonArr = [
   "{\"id\":\"b00a3a47-783a-4af5-90d9-59c4deb7a9e3\",\"notes\":\"sdfsdf\",\"recordType\":0}",
   "{\"id\":\"a6f72972-502e-452b-9773-51699a527122\",\"notes\":\"sdfsfdf\",\"recordType\":0}"
];

var filteredResult = jsonArr.filter(function(item) {
  return JSON.parse(item).id !== 'a6f72972-502e-452b-9773-51699a527122';
});

View the demonstration on JSFiddle here.

Answer №2

It appears that the strings need to be parsed as JSON. To address this issue, I have provided a solution that directly modifies the detailsArray by eliminating the problematic index. Here is an implementation of a callback-based kind of indexOf using Array.prototype.reduce

var index = detailsArray.reduce(function(prev, curr, idx) {
    return prev === -1 && JSON.parse(curr).id === detailId ?
        idx : prev;
}, -1);
if (index > -1) {
    detailsArray.splice(index, 1);
}

var detailsArray = [
      "{\"id\":\"b00a3a47-783a-4af5-90d9-59c4deb7a9e3\",\"notes\":\"sdfsdf\",\"recordType\":0}",
      "{\"id\":\"a6f72972-502e-452b-9773-51699a527122\",\"notes\":\"sdfsfdf\",\"recordType\":0}"
   ],
   detailId = 'a6f72972-502e-452b-9773-51699a527122';
    
var index = detailsArray.reduce(function(prev, curr, idx) {
  return prev === -1 && JSON.parse(curr).id === detailId ?
    idx : prev;
}, -1);
if (index > -1) {
    detailsArray.splice(index, 1);
}

document.getElementById('out').innerHTML += JSON.stringify(detailsArray, null, '  ');
<pre id="out">detailsArray = </pre>

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

Passing a variable between functions in JavaScript: Tips and tricks

let chart; let data = new Array(); function handleClick() { data = document.getElementById('graph:hi').value; alert(data); } let chartData = new Array(66, 15, 2.5, 21.9, 25.2, 23.0, 22.6, 21.2, 19.3, 16.6, 14.8); alert(chartData); jQuery ...

Are these two sections of my code distinctive in functionality? Do they both address potential errors in the same manner?

After receiving some helpful suggestions on my code from a user on stack overflow, I decided to revisit and make improvements. However, I am now questioning whether the changes I made handle errors in the same way as the original code. This is my initial ...

The cursor is located on the right side instead of the usual left side

Why is the cursor positioned on the right side rather than the left side? $('.legoact').focus(); When the cursor is positioned on the right side, it can be achieved using the following CSS properties: .lego{ background:#ddd; width:70%; m ...

When dealing with errors in fetching JSON data, consider implementing a robust error handling strategy and

Is there a way to provide a fallback JSON string in case the fetch URL fails to connect? const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`) ...

"Implementing React to dynamically load and update value in component, enabling user interaction with the

As a newcomer to the world of React (16.4.2), I am trying to grasp its functionality without delving into Redux just yet; my focus is solely on understanding the core React library. In my application, there is an input component called RangeInput, which r ...

Struggling to make Reactable work with React Native because of the error "Invariant Violation: View config not found for name input"

After attempting to follow a tutorial on creating tables with React for my React Native app, I consistently encountered errors such as "Invariant Violation: View config not found for name th." Even when trying to run the source code provided in the tutoria ...

Steps for saving data to a JSON file in a React application

Looking to update a json file with some data. The current contents of the JSON file are: [{"name":"Flossi","image":"https://robohash.org/istevelitut.png?size=50x50&set=set1","price":49,"info": ...

Ways to move down only one level of an element's children, excluding sub-levels

When implementing this code snippet: jQuery: $(this).next().slideDown() with a selector :$(this).next() HTML: <li class="sub-menu two-level-collapse"> <a href="javascript:void(0);" class="two-level-collapse parent">< ...

Is it possible to update JavaScript on mobile devices?

I'm currently working on a mobile site where I've implemented JavaScript to refresh a message counter. However, despite having JavaScript enabled on the device, the counter doesn't update on my Nokia e90. Interestingly, it works perfectly fi ...

Prettier eliminates the need for parentheses in mathematical expressions

When working with mathematical expressions in React and attempting to slice an array based on those expressions, I encountered an issue with the Prettier extension. It automatically removes parentheses from the expressions, resulting in incorrect calculati ...

Seeking assistance to prevent data duplication when transferring information from list1 to list2 in React.js

As I work on developing two lists in React.js, I encountered an issue with avoiding repetitions when transferring items from list-1 to list-2. I need assistance creating a function that prevents duplicate items in list-2 while also ensuring that the items ...

Should I wait for my state to be updated with new information before triggering the render function?

Can someone assist me with restructuring the code below to ensure that the information in the data array is displayed on the initial page load? async componentDidMount() { const { id } = this.props.match.params const soccerApi = axio ...

Troubleshooting issue: Chrome bug causing JavaScript full height intro section to have incorrect padding and display issues

Trying to create a full-height intro section using basic JavaScript markup has been quite the challenge. Here's a more detailed explanation: I have a parent DIV element that is supposed to adjust to the full height of the viewport. Unfortunately, t ...

Would parallax stars be overwhelming for a webpage?

I'm a newcomer to the world of web development and I have an idea to make stars move across my website. However, I'm concerned about whether this might be too much for a simple website to handle. Is there a way to optimize the code? const canvas ...

The data submitted from the form did not successfully get inserted into the database row

Currently, I am working on integrating a new product into my products database using ajax with php and mysql PDO. The form is located in a separate HTML file and gets loaded into a Bootstrap modal when the "add product" button is clicked. Below you can fi ...

Switch out a specific string within a JavaScript object

{ 1:' {person} experimenting for 1 ', 2:'{person} experimenting for 2 ', 3:'{person} experimenting for 3 ', 4:'{person} experimenting for 4 ', 5:'{person} experimenting for 5 ' } Imag ...

Improvement in Select2 Change Event: Update the subsequent select2 box options based on the value change in the preceding select2 box

I need assistance with two select boxes, namely Category and Sub-category. My objective is to dynamically alter the available options in the subcategory box based upon the value selected in the category box. Additionally, I would like to load data for the ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...

Using jQuery to adjust the length of a string to fit within a specific width

I am working with a table and need to input strings in each cell, but they are wider than the cell width. I want to shorten the strings without breaking lines, and add '...' at the end to show that the string is long. The table consists of aroun ...