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

Converting a struct to an array format without keys using serialization and deserialization

Is there a way to serialize and deserialize a struct without specifying keys? By using indexes as keys, the order of fields can be preserved which would result in a smaller payload size. I am currently utilizing serde_json and ciborium crates, both of whi ...

Divide Array of Strings in a DataFrame into separate columns

I currently have a dataframe that looks like this: df.show() +-----+ |col1 | +-----+ |[a,b]| |[c,d]| +-----+ Is there a way to transform it into the following dataframe? +----+----+ |col1|col2| +----+----+ | a| b| | c| d| +----+--- ...

What steps should I take to modify this recursive function so that it can verify the property name of an object?

I stumbled upon the code snippet below online, which effectively and recursively eliminates properties from an object if their values are null, undefined, or 0 const removeEmpty = (obj) => { Object.keys(obj).forEach(key => (obj[key] & ...

Navigating through two nested arrays in JavaScript to access an object

Having difficulty extracting the nested car values using JavaScript (lodash). Take a look at the JSON data below: { "cars":[ { "nestedCars":[ { "car":"Truck", "color" ...

"The controller seems to always return an 'undefined' value for the Angular

Within my project, I have implemented ui-view with the following structure: <main class="content"> <div class="inner" ng-controller="OrderPageController"> <div ui-view="main-info"></div> <div ui-view="comment ...

Mysterious dual invocation of setState function in React

My component is designed to display a list of todos like: const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery shopping", completed: false }, ]; ...

Getting the input from an HTML editor and inserting it into a textarea using JavaScript

Currently, I am in the process of developing an HTML editor for a project. I have downloaded a program online that I am attempting to customize according to my requirements. However, I am encountering difficulties when trying to retrieve the inner HTML of ...

Top eCommerce frameworks optimized for Web2 and SaaS integration

Are there any payment and eCommerce frameworks that can seamlessly integrate with a REST-based application right out of the box? My server is Java-based, but I've found limited options in this area. I'm open to wrapping my interface with another ...

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...

Tips for integrating an HTML template into a React project

I'm finding it challenging to integrate an HTML template into React. The template I am using is for an admin dashboard with multiple pages. I have successfully copied and pasted the HTML code into JSX files and fixed any syntax issues. Here's wh ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

The functionality of the dynamic text box is disrupted when a form element is added

I am in the process of developing a form and am looking to create dynamic text boxes using Bootstrap. The code that I have currently works as expected: $(function() { $(document).on('click', '.btn-add', function(e) { e.preventD ...

Steps for toggling between enabling and disabling the 2 instances of bvalidator

Running on my form are two instances of bvalidator found at . The first instance validates the entire form, while the second instance only partially validates the same form. In total, the form contains 2 buttons: The first button saves form data upon va ...

Unit testing in AngularJS: Initializing the controller scope of a directive

Here is the code for a directive with a separate controller using the "controller as" syntax: 'use strict'; angular.module('directives.featuredTable', []) .controller('FeaturedTableCtrl', ['$scope', function ($sco ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

Automated tool for generating random JSON objects

Looking for a tool that can generate random JSON objects? I'm in need of one to test my HTTP POST requests and incorporate the random JSON object into them. Any recommendations? ...

What is the best way to create a variable in a React component that requires asynchronously loaded data in order to be functional?

While I have a good understanding of passing data from one component to another using this.props, I am encountering difficulty in asynchronously fetching and storing values, such as from a database, that need to be accessed throughout the component. The ch ...

Transmit responses from PHP script

I am in the process of creating a signup form where, upon clicking the submit button, all form data is sent to a PHP file for validation. My goal is to display an error message next to each input field if there are multiple errors. How can I achieve this ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...