Save unique pairs of keys and values in an array

I'm faced with extracting specific keys and values from a JSON data that contains a variety of information. Here's the snippet of the JSON data:

    "projectID": 1,
    "projectName": "XXX",
    "price": 0.2,
    "regStart":{
        "$date": "2021-12-15T16:00:00.00Z"
    },
    "regEnd":{
        "$date": "2021-12-18T16:00:00.00Z"
    },
    "saleStart":{
        "$date": "2021-12-20T20:00:00.00Z"
    },
    "saleEnd":{
        "$date": "2021-12-15T20:00:00.00Z"
    },
    "totalRaise": 200000,
    "totalSale": 50000,
    "projectStatus": "Ongoing",

My goal is to extract and store only projectID, projectName, and price. However, I'm unsure how to iterate through this data and save it to my empty object.

    let result = []
    for(let i=0;i<data.length;i++){
      let tempRes = {}
      // ...no idea how to do it
      result.push(tempRes);
    }

Answer №1

const information = {"projectID": 1,
    "projectName": "CompanyABC",
    "price": 0.2,
    "regStart":{
        "$date": "2021-12-15T16:00:00.00Z"
    },
    "regEnd":{
        "$date": "2021-12-18T16:00:00.00Z"
    },
    "saleStart":{
        "$date": "2021-12-20T20:00:00.00Z"
    },
    "saleEnd":{
        "$date": "2021-12-15T20:00:00.00Z"
    },
    "totalRaise": 200000,
    "totalSale": 50000,
    "projectStatus": "Ongoing"}

const selectedInfo = {};


    Object.keys(information).forEach(key=>{
            if(['projectID','projectName','price'].includes(key)) {   // you can customize this as needed
            selectedInfo[key] = information[key];
    }

});


console.log(selectedInfo);

Answer №2

To access the property, you can use dot notation. For instance:

var info = {
  "userID": 1,
  "username": "JohnDoe",
  "email": "johndoe@example.com",
  "joinedDate": {
    "$date": "2022-01-01T00:00:00.00Z"
  },
  "lastLogin": {
    "$date": "2022-01-15T12:00:00.00Z"
  }
}

var userDetails = {userID: info.userID, username: info.username, email: info.email}

console.log(userDetails)

Answer №3

I wanted to share a useful function that I created some time ago.

function removeKeys(obj, keys, deepClone = true) {
  const cloneObject = deepClone ? obj : JSON.parse(JSON.stringify(obj));
  keys.forEach((key) => {
    if (Object.hasOwnProperty.call(cloneObject, key)) {
      delete cloneObject[key];
    }
  })

  return cloneObject;
}

You can use it in your specific case like this:

const newPayload = removeKeys(data, ['regStart', 'regEnd', 'saleStart', 'saleEnd', 'totalRaise', 'totalSale', 'projectStatus'], false);

See it in action here: JSFiddle

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

Learn how to effectively utilize templateURL in an express and angular project

Our project utilizes Express without any view engine. To set up static directories, we have the following: app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/view')); app.use(express.static(__dirname + ...

The implementation of JSON Schema draft 4 now supports unordered arrays

Seeking a schema solution that allows the addition of multiple addresses based on specific criteria: 1) Must include Correspondence address 2) Must include Residence address 3) Other address types are optional 4) Addresses can be listed in any order Ca ...

How can I populate a form in Meteor with data from a MongoDB collection that was previously inserted?

Recently, I completed constructing a lengthy form field where users can enter a plethora of information. This form consists of various text and number fields, radio button sets, and checkbox groups. The data is successfully saved in a Mongo collection with ...

Retrieving user and groups information using Express.js and Node.js with OKTA

Is anyone else experiencing an issue with retrieving user info and group info using the OKTA API? The responses are being sent as strings, requiring me to use JSON.parse() before I can work with the data. Has anyone found a solution to this problem? ...

Is it possible to automatically mute an HTML 5 video when closing the modal?

Is there a way to pause a video that plays in a modal and continues playing in the background when the modal is closed? I am using the Materialize library. <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <!-- Compiled ...

Experiencing ERR_TOO_MANY_REDIRECTS while using Next.js with Vercel and a Custom Domain through Cloudflare

I'm having trouble getting my Next.js project set up on Vercel with a custom domain managed through Cloudflare. Despite configuring the DNS and SSL settings correctly, I keep seeing a net::ERR_TOO_MANY_REDIRECTS error when trying to access my site at ...

JS is programmed to automatically redirect the user after they have clicked on a div element and a

I'm having trouble with this code that is supposed to redirect a user after they click on the div and then the next button. It's not working for me :( Here is the code I am using: $("a.xxx").click(function() { $(this).toggleClass("yyy"). ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Obtain real-time information from an object using React

After developing an app using React, I encountered a scenario where I needed to work with data from an API. Here is the object structure: let currency = { "success": true, "timestamp": 1648656784, "base": "EUR", &quo ...

Access information through the restful api using the angularjs service $resource

I am attempting to utilize the $resource service with the surveygizmo API. Here is my code: HTML : <div ng-app="Survey"> <body> <div ng-controller="SurveyCtrl"> {{survey.data.title}} </div> </body> </div> My scr ...

Discovering complimentary number sequences amidst intersecting number sequences

I have a specific number of arrays, each containing a set amount of elements. Each element consists of two attributes represented by numbers. { start: x end: y } These start and end numbers define a range, where the start value is always smaller tha ...

Strange Date Format in an API

I've come across an issue that I can't seem to find a solution for, and I was wondering if anyone here could assist me. While working with the API of one of our products at work, I've noticed that a date field is returned in two different fo ...

Issue with callback function not triggering after comment deletion in REACT

Although I am successfully able to delete the comment, I am facing an issue where the callback function is not being invoked. My suspicion is that it might be related to how I pass multiple arguments to the function, but I cannot confirm this. Below is th ...

Is there a way to identify and remove empty spaces and carriage returns from an element using JavaScript or jQuery?

Is there a way to easily remove empty elements from the DOM by checking if they contain only whitespace characters or nothing at all? I am attempting to use $.trim() to trim whitespace in empty elements, but some are still returning a length greater than ...

What is the optimal approach: Extracting HTML from a jQuery response?

Just wondering how people handle this situation...if a user adds something to a list and, when it's done, triggers the following ajax code to update the .user-stream-list $.ajax({ url: "user-stream-list.php", success: function(data){ ...

What is the best way to iterate through draw.rectangle in Pillow using Python?

I am seeking to extract facial coordinates from a JSON file structured like this: #Snippet FROM JSON FILE { "image": { "height": 2160, "orientation": 1, "width": 3840 }, "objects": [ { "boundingBox": ...

What is the method for verifying PHP information using jQuery AJAX?

On my PHP page, I have an else statement that filters data from a SQL database based on user input. Below is some pseudo code: NextPage.php //Include database configuration file include('../dbConfig.php'); if(isset($_POST['pageno']) ...

JavaScript functioning properly in Google Chrome and Firefox but not in Internet Explorer 9

Welcome to the Lottery random generator tool! Feel free to use this in Google Chrome or Firefox, but please note that it may not work properly in Internet Explorer 9. If you encounter any issues while using this tool on IE9 and receive an error message st ...

Ways to direct to a specific div upon clicking an anchor tag following a page reload?

<a href="#goto">Link 1</a> <div id="goto">DIV</div> Whenever I click on the anchor tag, my webpage reloads and displays a new div with the ID of goto. This div was previously hidden but is now visible at the bottom of the page. I ...

Combining Arrays in AngularJS: A Step-by-Step Guide

I have two arrays with dynamic values: $scope.objectName = [{ Name: '' }]; $scope.propertiesElement = [{ Key: '', Value: '' }]; How can I concatenate these arrays to achieve the following result? [{Name:''},{ Key: ...