remove unnecessary parameters from a JavaScript object using curly braces

My query pertains to an object response below

result.joblist = {
  "collection_job_status_list": [
    {
      "application_context": {
        "application_id": "a4",
        "context_id": "c4"
      },
      "creation_time": "15699018476102",
      "progress": 100,
      "status": "READY",
      "phase": "ACTIVE",
      "job_error": {}
    },
    {
      "application_context": {
        "application_id": "a6",
        "context_id": "c6"
      },
      "creation_time": "15698648632523",
      "progress": 100,
      "status": "READY",
      "phase": "ACTIVE",
      "job_error": {}
    }
  ],
  "result": {
    "request_result": "ACCEPTED",
    "error": {}
  }
}

I need to extract only

application_id":"a4","context_id":"c4"
without the surrounding
{"application_context": & ending }
.

I attempted a solution but am facing issues moving forward.

var newObj: any = {};
if (allJobs && allJobs.length > 0) {
  // this.rowData = this.allJobs;
  // this.allJobs = this.allJobs['application_id'];
  //let ele:object = allJobs.application_context;
  allJobs.forEach(ele => {
    newObj = {
      application_id: ele.application_context.application_id,
      context_id: ele.application_context.application_context
    };
    return newObj;
  });
}

Answer №1

To achieve the desired outcome, utilize the map function along with destructuring

  • Retrieve the collection_job_status_list from the result object
  • Iterate over the values, extract the necessary data from the application_context property, and combine it with the remaining values
  • Recreate the original structure as found in the result object

let result = {"collection_job_status_list": [{"application_context": {"application_id": "a4","context_id": "c4"},"creation_time": "15699018476102","progress": 100,"status": "READY","phase": "ACTIVE","job_error": {}},{"application_context": {"application_id": "a6","context_id": "c6"},"creation_time": "15698648632523","progress": 100,"status": "READY","phase": "ACTIVE","job_error": {}}],"result": {"request_result": "ACCEPTED","error": {}}}

let { collection_job_status_list, ...rest } = result

let modified = collection_job_status_list.map(({
  application_context: {
    application_id,
    context_id
  },
  ...rest
}) => ({ ...rest, context_id, application_id}))

let final = {
  collection_job_status_list: modified,
  ...rest
}

console.log(final)

Answer №2

To solve this, it's essential to utilize a map. For more information, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Make the following adjustments to the code for the desired result:

let newObj: any = {};
let newArray;
if (allJobs && allJobs.length > 0) {
  newArray = allJobs.map(item => {
    newObj = {
      application_id: item.application_context.application_id,
      context_id: item.application_context.application_context
    };
    return newObj;
  });
}

Hopefully, this solution resolves the issue :)

Answer №3

To implement the functionality, the map function is necessary

const result = {};
result.joblist = {
  "collection_job_status_list": [
    {
      "application_context": {
        "application_id": "a4",
        "context_id": "c4"
      },
      "creation_time": "15699018476102",
      "progress": 100,
      "status": "READY",
      "phase": "ACTIVE",
      "job_error": {}
    },
    {
      "application_context": {
        "application_id": "a6",
        "context_id": "c6"
      },
      "creation_time": "15698648632523",
      "progress": 100,
      "status": "READY",
      "phase": "ACTIVE",
      "job_error": {}
    }
  ],
  "result": {
    "request_result": "ACCEPTED",
    "error": {}
  }
}


result.joblist.collection_job_status_list = result.joblist.collection_job_status_list.map(item => {
  return {
     "application_id": item.application_context.application_id,
     "context_id": item.application_context.context_id
  }
})

console.log(result)

Alternatively, the map function can be used with shorthand es6 syntax

const result = {};
result.joblist = {
  "collection_job_status_list": [
    {
      "application_context": {
        "application_id": "a4",
        "context_id": "c4"
      },
      "creation_time": "15699018476102",
      "progress": 100,
      "status": "READY",
      "phase": "ACTIVE",
      "job_error": {}
    },
    {
      "application_context": {
        "application_id": "a6",
        "context_id": "c6"
      },
      "creation_time": "15698648632523",
      "progress": 100,
      "status": "READY",
      "phase": "ACTIVE",
      "job_error": {}
    }
  ],
  "result": {
    "request_result": "ACCEPTED",
    "error": {}
  }
}


result.joblist.collection_job_status_list = result.joblist.collection_job_status_list.map(({application_context}) => {
  return {
     ...application_context
  }
})

console.log(result)

UPDATE:

The content to include in your array is based on the items returned from the map. You select the keys to retain. For instance, if you require other items.

If there is an array A

A = [
  {
    nest: {
      x: 1,
      y: 1,
    },
    key1: 5,
    key2: 7,
  },
  {
    nest: {
      x: 1,
      y: 1,
    },
    key1: 5,
    key2: 7,
  },
  {
    nest: {
      x: 1,
      y: 1,
    },
    key1: 5,
    key2: 7,
  }
]

Assume you want x from nest, key1 and key2 in the final output. You would do

const finalOutput = A.map(item => {
  return {
     x: item.nest.x, // x from nest
     key1: item.key1, // key1
     key2: item.key2,  // key2
  }
})

A quicker approach exists for this. For instance, if the item in the map function is already separated into a nest and a rest variable where nest includes item.nest and rest is {key1: 5,key2:7}, you can simply return x from nest and all else from rest

const finalOutput = A.map(({nest, ...rest}) => {
  return {
     x: nest.x, // x from nest
     ...rest, // all remaining keys
  }
})

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

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...

Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue. How can I ensure that all calls are finished before invoking window.location.href? Code: const ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

React's `setState` function seems to be failing to update my rendered catalog

Managing a shopping catalog where checkboxes determine the rendered products. The list of filters serves as both the menu options and state variables. The actual products in the products list are displayed based on the selected categories. const filters ...

Unable to connect to server using React-Native fetch. Localhost is not being used

I recently encountered an issue with my app where the fetch function used for user authentication stopped working. Despite not making any changes, the transition from React 0.27 to 0.28 seemed to have caused this problem. After scouring through numerous S ...

What is the best way to display HTML content inside a pop-over window?

How can I load popover content from another HTML file using templateUrl in AngularJS? Check out the demo below: HTML: <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8"/> <title>AngularJS Plunker& ...

Node Js issue stemming from unaddressed promises leading to rejection

Hi, everyone! I'm currently facing some challenges while trying to deploy this API. The error message I keep getting is: "UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error may have occurred due to either throwing inside an asyn ...

How to disable a specific date in Bootstrap datepicker?

I need to deactivate specific dates using bootstrap <script> $(document).ready(function(){ var date_input=$('input[name="date"]'); var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form') ...

Refresh Form (Reactive Forms)

This is the HTML code snippet: <div class="container"> <ng-template [ngIf]="userIsAuthenticated"> <form [formGroup]='form' name="test"> <div class="form-group"> <input type="text" class="form-contr ...

Firebase scheduled function continues to encounter a persistent issue with an "UNAUTHENTICATED" error being consistently thrown

I have created a firebase-function that is scheduled to retrieve data from an external API source and save it in Firestore. const functions = require("firebase-functions"); const admin = require("firebase-admin"); const { default: Axios ...

Unable to locate the index.js entry file in React Native

I have a simple React Native application. I am attempting to test it on a virtual Android device by navigating to the project and running npm start -- --reset-cache. After terminating the process, I enter the command react-native run-android. Despite havin ...

Having trouble integrating NEXT AUTH with Firebase due to an error: "Cannot import statement outside

Let's take a look at our firebase configuration file: import { getFirestore } from "firebase/firestore"; export const firebaseConfig = { apiKey: process.env.FIREBASE_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: pr ...

What could be causing my AJAX form to refresh the page upon submission?

I have been working on a basic Follow/Unfollow system, and although the functionality is working correctly in terms of inserting and deleting rows when following/unfollowing, I'm facing an issue where the page refreshes every time despite using e.prev ...

Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code: const VMList = new Vue({ el: '#MODAL_USER_DATA', data: { user: []//, //userAcc: [] }, met ...

Guide for animating individual mapped elements in react-native?

After mapping an object array to create tag elements with details, I added an animation for the tags to zoom in on render. However, I wanted to take it further and animate each tag individually, sequentially one after the other. This appears to be a common ...

What is the reason behind the TypeScript HttpClient attempting to interpret a plain text string as JSON data?

When utilizing Angular TypeScript, I have implemented the following approach to send a POST request. This request requires a string parameter and returns a string as the response. sendPostRequest(postData: string): Observable<string> { let header: ...

Leveraging Watchers on props in Vue 3's Script Setup

When passing a prop to a component that declares its state, I am attempting to watch the prop and set the CSS styling accordingly. However, for some reason it is not working as expected. Can anyone help me figure out what might be wrong? <script setup ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

Obtain a report using a variety of different conditions

My database has a table with the following fields: TPI CLICKS IMPRESSION CLASSIFY I am looking to retrieve 3 specific results: 1) Calculate SUM(CLICKS)/SUM(IMPRESSION) * 100 GROUPED BY TPI 2) Calculate SUM(IMPRESSION) WHERE CLASSIFY = "XYZ" GROUPED BY ...