How to eliminate unnecessary JSON data using JavaScript

Recently delving into the realms of JSON and JavaScript, I found myself tasked with creating a table in Cloudant NoSQL. Upon gathering Weather data from a reliable Weather Company in JSON format to upload onto Cloudant, I encountered some irrelevant data that didn't align with the table I aimed to construct. Is there a method using JavaScript to eliminate the metadata and the column name "observation" from the received JSON data?

This is the JSON data at hand:

{
  "metadata": {
    "language": "en-US",
    "transaction_id": "1503766402801:1454518918",
    "version": "1",
    "latitude": 12.83,
    "longitude": 77.68,
    "expire_time_gmt": 1503771300,
    "status_code": 200
  },
  "observation": {
    "key": "43295",
    "class": "observation",
    "expire_time_gmt": 1503771300,
    "obs_id": "43295",
    "obs_name": "Bangalore",
    "valid_time_gmt": 1503759600,
    "day_ind": "N",
    "temp": 75,
    "wx_icon": 29
  }
}

The desired JSON structure is as follows:

{
    "_id": "2e5e0da1f82157dd6f5d381a4c9ff84e",
    "_rev": "1-b7a92ae5f96b051f0add3b26a14543c2",
    "key": "43295",
    "class": "observation",
    "expire_time_gmt": 1503771300,
    "obs_id": "43295",
    "obs_name": "Bangalore",
    "valid_time_gmt": 1503759600,
    "day_ind": "N",
    "temp": 75,
    "wx_icon": 29
}

Thank you for any assistance.

UPDATE: While I managed to remove the metadata using "delete data.metadata;" where 'data' holds the JSON, I am still facing challenges removing the word "observation" and the curly braces towards the end.

Answer №1

To simplify your JSON data, you can extract all keys from nested objects and combine them into a new object.

var myData = {
  "metadata": {
    "language": "en-US",
    "transaction_id": "1503766402801:1454518918",
    "version": "1",
    "latitude": 12.83,
    "longitude": 77.68,
    "expire_time_gmt": 1503771300,
    "status_code": 200
  },
  "observation": {
    "key": "43295",
    "class": "observation",
    "expire_time_gmt": 1503771300,
    "obs_id": "43295",
    "obs_name": "Bangalore",
    "valid_time_gmt": 1503759600,
    "day_ind": "N",
    "temp": 75,
    "wx_icon": 29
  }
}

myData = Object.keys(myData)
    .reduce((res, key) => Object.assign(res, myData[key]), {});

console.log(myData);

There seems to be some additional keys in the result that are unexpected. Unclear where they originated from.

If there are surplus properties to remove, you may utilize delete method for elimination.

["latitude", "longitude"].forEach(k => delete myData[k]);

Alternatively, if I misinterpreted your requirement. If you only seek the observation object, just reassign it back to the initial variable.

myData = myData.observation;

You can then include any other desired properties.

Answer №2

One approach to consider when sending data is to create a fresh JSON object beforehand. Leveraging lodash can simplify the process of extending objects.

// Let's say 'result' contains your json information
var customJson = _.extend({}, result.observation, result.metadata);

Answer №3

If the sequential arrangement of elements is not a concern, then this approach provides a straightforward solution:

var data = {
  "metadata": {
    "language": "en-US",
    "transaction_id": "1503766402801:1454518918",
    "version": "1",
    "latitude": 12.83,
    "longitude": 77.68,
    "expire_time_gmt": 1503771300,
    "status_code": 200
  },
  "observation": {
    "key": "43295",
    "class": "observation",
    "expire_time_gmt": 1503771300,
    "obs_id": "43295",
    "obs_name": "Bangalore",
    "valid_time_gmt": 1503759600,
    "day_ind": "N",
    "temp": 75,
    "wx_icon": 29
  }
}
var newData = data.observation;
newData._id = "2e5e0da1f82157dd6f5d381a4c9ff84e",
newData._rev = "1-b7a92ae5f96b051f0add3b26a14543c2";
console.log(newData);

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

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

Touch Screen Button Interaction

Planning to create a Kiosk website with HTML5 that includes point and drag & drop functionality. The site will have buttons and images for user interaction, with actions triggered by finger touches on the screen instead of mouse clicks. Would it be more ...

Tips on how to bring in a module from index.js

Recently, I set up a sample node.js project: "name": "example", "version": "1.0.0", "type": "module", Let's take a look at the index.js (only two lines): "use strict"; import ...

Convert CSV into an object with additional attribute

I'm attempting to import data from a CSV file into a d3 tree graph. While I've successfully loaded the JSON version of the data, the d3.csv parser isn't returning the expected string. Some approaches I've tried include: treeData.forEa ...

Map will be visible correctly only when the window is resized

I'm currently working on a project that utilizes a map engine from a private company which I am unable to disclose. The initial system was built in JQuery, but we recently underwent significant changes and now have it running on AngularJS. One side ...

What is the step-by-step process for incorporating the `module` module into a Vue project?

ERROR Compilation failed with 6 errors 16:20:36 This specific dependency could not be located: * module in ./node_modules/@eslint/ ...

Ensure that the entire webpage is optimized to display within the viewport

My goal is to make the entire website fit perfectly into the viewport without requiring any scrolling. The main pages I am focusing on are index, music, and contact, as the other two pages lead to external sources (you can find the link at the bottom of th ...

Attempting to modify an object's property while maintaining reactivity, unfortunately encountering an issue with the property or method "vm" not being defined on the instance despite being referenced during the render

Up to this point, I've been attempting to set the value of an object property to false using @click='review.isActive = true'. However, it appears that Vue cannot detect these changes, causing the property to not be reactive. According to th ...

Tips for inserting a jQuery snippet into a universal file

Seeking some advice on integrating jQuery code into my JavaScript file, which is located at . The code snippet I am attempting to add looks like this: $(document).ready(function() { queue = new Object; queue.login = false; var $dialog = $ ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

Locate every item that has a value that is not defined

My data is stored in indexeddb, with an index on a text property of the objects. I am trying to retrieve all objects where this property's value is undefined. I have been experimenting with IDBKeyRange.only(key), but when I use null, undefined, or an ...

Uncovering the potential of JSON data using PHP

I recently retrieved information from a different website in JSON format. You can see what I found here: Specifically, I am looking to obtain the values for kills and deaths from this data set. I attempted using the php function json_decode() on this info ...

Avoid duplication of elements in Angular applications

Currently, I have a component that loads animated divs based on a datasource. *Note: In the example, I've used a lot of <any> because I haven't finalized the model yet. apiService.ts dataArray: Observable<Array<any>>; constru ...

What is the best way to automatically remove a Firebase database entry when a user has been inactive for a period of time, without logging out but simply not accessing the page for an extended duration?

Currently, when a user clicks 'logout', their session is terminated, and a database entry is removed. All other users can see that database entry, so the objective is for users to view each other's data only while they are logged in. For in ...

Exploring the Power of 2D Arrays in JavaScript

Hey there! I'm having trouble defining a 2D array in JS. Two errors are getting in my way and I can't figure out what's going wrong. i is generated by a for loop - it's defined. Even when I try replacing i with 0, the same error occurs. ...

Unpacking Functions within Embedded Redux Reducer

My current challenge involves dispatching an action that has the following structure: { type: "TOGGLE_FARA", fara: true, id: "5d20d019cf42731c8f706db1" } The purpose of this action is to modify the "enabled" property within my "fara" state. The configura ...

Update the pageExtensions setting in Next.js to exclude building pages with the file extension *.dev.*

I am currently working on a project using Next.js version v12.3, and I have encountered an issue related to excluding page files with a *.dev.* extension from the build process. In my configuration file next.config.js, I have configured the pageExtensions ...

Importing JSON data into a pandas data frame and defining personalized fields

Examining this sample JSON data as part of my current project. { ":@computed_region_amqz_jbr4": "587", ":@computed_region_d3gw_znnf": "18", ":@computed_region_nmsq_hqvv": "55", ":@computed_region_r6rf_p9et": "36", ":@computed_region_ra ...

AngularJS fails to recognize Iframe element during REST request

I'm having trouble with my webpage only reading the Iframe tag. It's sending the content correctly according to Postman. Postman is giving me this content: "Conteudo": "<p>Test iframe:</p>\n\n<p><iframe framebord ...