Remove a field from a JSON array

Consider the following JSON array:

var arr = [
{ID: "1", Title: "T1", Name: "N1"}, 
{ID: "2", Title: "T2", Name: "N2"}, 
{ID: "3", Title: "T3", Name: "N3"}
]

Is there a way to remove the Title key from all rows simultaneously without using a loop?

The resulting array should be:

var arr = [
{ID: "1", Name: "N1"}, 
{ID: "2", Name: "N2"}, 
{ID: "3", Name: "N3"}
]

I attempted the code below:

delete arr.Title

But it only returns a logical response of "true" instead of the updated array.

Answer №1

you were not too far off:

[edit] consider these alternative solutions: 1) Implement forEach or for..of loop. 2) Use delete or Reflect.deleteProperty method.

let
  arr_1 = [
    {ID: 1, Title: "T1", Name: "N1"},
    {ID: 2, Title: "T2", Name: "N2"},
    {ID: 3, Title: "T3", Name: "N3"}
  ],
  arr_2 = arr_1.map(e=>Object.assign({},e)) // create a new array of copies
;

// solution 1
arr_1.forEach(elm=>delete elm.Title)

// solution 2
for(let elm of arr_2){ Reflect.deleteProperty(elm, 'Name') } // update

console.log('arr_1 =', JSON.stringify(arr_1))
console.log('arr_2 =', JSON.stringify(arr_2))

Answer №2

An alternative method involves using the map function to generate a new array with the desired output. Within the handler, a new Object is created using the object from each index, and then the unwanted property name Title is removed.

If you were referring to an array, this approach ensures that the original objects remain unchanged.

let arr = [{ID: "1", Title: "T1", Name: "N1"}, {ID: "2", Title: "T2", Name: "N2"}, {ID: "3", Title: "T3", Name: "N3"}],
    result = arr.map(o => {
      let obj = Object.assign({}, o);
      delete obj.Title;
      return obj;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

If you're aiming to avoid using a loop in your code, there are alternative approaches we can take. While JavaScript doesn't provide a direct method for mass operations on list elements like some other languages do, such as APL and K, we can utilize tools like map to abstract the looping process. However, it's important to note that even when using map, there is still an underlying looping mechanism at play.

var arr = [
  {ID: "1", Title: "T1", Name: "N1"}, 
  {ID: "2", Title: "T2", Name: "N2"}, 
  {ID: "3", Title: "T3", Name: "N3"}
]

const newArr = arr.map(({Title, ...rest}) => ({...rest}))

console.log(newArr)

Answer №4

When working with actual JSON strings, you can utilize the JSON.parse reviver parameter to filter or modify values :

var jsonData = '[{"ID":"1","Title":"T1","Name":"N1"},{"ID":"2","Title":"T2","Name":"N2"},{"ID":"3","Title":"T3","Name":"N3"}]'

var filteredArray = JSON.parse(jsonData, (key, value) => key != 'Title' ? value : void 0);

console.log( filteredArray );

Answer №5

The arr variable is mistakenly identified as an array, but it is actually an object.
Objects in JavaScript are enclosed in curly braces {}, such as:

{ "name":"Bob", "alive":true, "dead":false }

Arrays, on the other hand, are enclosed in square brackets [], like this: ["Bob","Jane","Mary"]

Answer №6

One effective approach is to utilize functional utilities that simplify the process of solving problems.

import { map, omit } from 'lodash/fp';
const modifiedArray = map(omit('Title'), originalArray);

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 best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Utilize vis.js to visualize networkx data in a visually interactive manner

Currently, I am utilizing the networkx Python library to construct a directed graph containing nearly 2k nodes. My goal is to visually represent this graph using the vis.js library. While I am able to export the graph as Json data, I am struggling to crea ...

There seems to be an issue where the program is unable to properly output the complete array of strings in C. It's either displaying nothing at all or just the first character

I am trying to print all the elements in this code using an array, but it is not working as expected. #include <stdio.h> #include <stdlib.h> //#include "student_info.h" int main() { char animals[3]; animals[0] = "lion&q ...

Is there a way to create a blurred background effect while the popup is in use?

I prefer my popup to have a dark or blurred background when active. The popup itself should remain the same, with only the background being darkened. I would like a dark layer overlaying the entire page. This script should be compatible with any website wh ...

Identify the mouse's location in relation to its parent element, not the entire webpage

A script I've been working on detects the mouse position relative to the page, taking into account a movement threshold of 100px before triggering certain actions. // Keep track of last cursor positions var cursorDistance = 0; var lastCursorX = null; ...

How to retrieve the index upon clicking in Javascript

In my 3d art gallery project, I am utilizing plain JavaScript. The task at hand involves populating certain columns with images by pulling from an array of image sources. On click, I need to retrieve the index of the clicked image so that I can extract add ...

The font size varies depending on the language being used

On a single web page, there are 3 different language words displayed: Language / 한국어 / ภาษาไทย I am interested in enlarging the Thai word (ภาษาไทย) to make it stand out. <span class="thai">ภาษาไท ...

The function jQuery.post is transmitting special characters encoded

After creating a string using recipeBlob = JSON.stringify(recipeData), I noticed that when sending it via $.post, the received data at my PHP script is showing up with escaped characters like this: {\"properties\":{\"Energy\":{\"v ...

Ways to access every element within an array from a Vue response

Is there a way to access the full course array?https://i.sstatic.net/Nxkhb.png The code snippet provided above only retrieves the first course array. <div class="form-group" v-show="school === 'SOSE'"> <label for="course">Cou ...

Execute javascript function upon user scrolling to a designated section in the webpage

Is there a method to trigger a unique function every time a user scrolls to a different div or section of the page? ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

Encountering the issue of receiving an error message that says "emitted value instead of an instance of error while compiling template" when trying to set

Trying to set up a Vue table with the help of a Vue table plugin in my application through node module is proving to be challenging. An error keeps popping up when I try to use all Vue table components. I installed all Vue table plugins using npm and impor ...

Safari re-downloads background image when revisiting with jQuery CSS

Using jQuery to set a background-image on my website: $('.header-image').css('background-image', 'url(/img/image.jpg)'); However, upon returning to the page from Safari, the image is downloaded again, unlike Chrome and F ...

Tips for parsing RDF/XML in Node.js using rdflib.js or rdf-parser-rdfxml

I've been attempting to read and parse an rdf/xml file, possibly converting it into JSON or a JavaScript Object. Despite my efforts in searching through numerous node libraries, I have not come across a good example that provides clear documentation o ...

Utilize ZLIB and Node.js to create a compressed zip archive of a folder's contents

I need to compress all the files in a directory into a single ZIP file. Currently, I am using this code snippet: var fs = require('fs'); var tar = require('tar'); var zlib = require('zlib'); var path = require('path&apo ...

Exploring the intricacies of extracting nested information from the Rapid API platform

Greetings! I am relatively new to both stack overflow and python, so please forgive me if the formatting is not quite right. Just to note, I am utilizing VS Code. I am currently extracting data from a Covid-19 rapid API, which provides the data in JSON fo ...

Cube area to be filled

I am struggling to fill a cube with colors as it is only getting half of the figure filled. I suspect there might be an issue with the cubeIndices, but I'm having trouble figuring out how to make it fill everything. While I know I could use a cylinder ...

What is the best way to add a simple Search bar to the Material UI Data Grid component?

If we take a look at this data grid example: check it out here I'd like to incorporate a simple search bar similar to the one shown here Can someone provide guidance on how to add this feature to Data Grid MUI? ...

How can I programmatically adjust the center of a Google Maps v3 map?

I have a table with 2 columns. The first column contains a div with a Google map, while the second column has a panel that changes its width after a few seconds. On the map, there is a marker placed. Issue: When I click on a button that triggers setCente ...