Sort JSON data based on keys (not values)

I have the following JSON data:

json = [{
    "code3": "ALB",
    "asset": 9,
    "biodiversity": 4,
    "infrastructure": 15
}, {
    "code3": "GHN",
    "asset": 4,
    "biodiversity": 5,
    "infrastructure": 5,
}, {
    "code3": "TGO",
    "asset": 3,
    "biodiversity": 6,
    "infrastructure": 7
}]

My goal is to filter it down to the following using a for loop:

result = [{
    "code3": "ALB",
    "asset": 9
}, {
    "code3": "GHN",
    "asset": 4
}, {
    "code3": "TGO",
    "asset": 3
}]

I want to know the most efficient way to achieve this. I am aware that I could use

json.forEach(j => del j["infrastructure"] ...
or similar, but I specifically want to filter based on the keys code3, asset.

Answer №1

This code snippet demonstrates how to use the map method in JavaScript:

let json = [
     {
          "code3": "ALB",
          "asset": 9,
          "biodiversity": 4,
          "infrastructure": 15
     },
     {
          "code3": "GHN",
          "asset": 4,
          "biodiversity": 5,
          "infrastructure": 5,
      },
      {
           "code3": "TGO",
           "asset": 3,
           "biodiversity": 6,
           "infrastructure": 7
      }
];

let result = json.map(({code3, asset}) => ({code3, asset}));

console.log(result);

If you're unfamiliar with the map method, it creates a new array by applying a function to each element of the existing array.

  • The provided example above helps illustrate how the map method works in practice.
let nums = [0, 1, 2, 3];
let add1 = n => n + 1;

// These two statements are equivalent:
nums = [add1(num[0]), add1(num[1]), add1(num[2]), add1(num[3])];
nums = nums.map(add1);
  • The code also utilizes object destructuring to extract input values from the arrow function.
  • Moreover, object shorthand properties simplify returning results from the function.
let a = 'foo', b = 42, c = {};
let o = {a, b, c}

// o = { a: 'foo', b: 42, c: {} }

Understanding these concepts should enhance your comprehension and utilization of JavaScript programming.

Answer №2

To achieve this, you can utilize the .map method:

let data = [
     {
          "name": "John",
          "age": 25,
          "city": "New York"
     },
     {
          "name": "Alice",
          "age": 30,
          "city": "Los Angeles"
      },
      {
           "name": "Bob",
           "age": 21,
           "city": "Chicago"
      }
];

let newData = data.map(item => {
     return {
          name: item.name,
          age: item.age
     }
});

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

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

Creating subdocuments with input types in MERN stack using Apollo Sandbox and MongoDB mutations

These questions are specific to a Node server application built in JavaScript using express, apollo-server-express, mongoose, and graphql. Below is the content of the package.json file: { "name": "dimond-media-mern-app", "vers ...

Checkbox column within GridView allows users to select multiple items at once. To ensure only one item is selected at a

Currently, I am facing a challenge with dynamically binding a typed list to a GridView control within an asp.net page that is wrapped in an asp:UpdatePanel for Ajax functionality. One of the main requirements is that only one checkbox in the first column c ...

Creating JSON objects by using the list name as the key in Python

I'm a bit unsure when it comes to manipulating JSON and I am attempting to create a JSON file in this format: { "employee":"mike","brakes":"15,60","individual":"1","time":"8:00", "employee":"dany","brakes":"15,60","individual":"1","time":"8:00" } Es ...

Creating an engaging Uikit modal in Joomla to captivate your audience

I need help optimizing my modal setup. Currently, I have a modal that displays articles using an iframe, but there is some lag when switching between articles. Here is the JavaScript function I am using: function switchTitleMod1(title,id) { document.g ...

What is the reason for the clearInterval consistently functioning after the completion of the function?

Just starting out in web programming and currently delving into javascript and jquery ajax.. This snippet represents my javascript code. The refresh variable controls an interval for updating the chat by fetching chats from the database and displaying the ...

Encoding a multidimensional associative array into JSON using PHP

Having used php's json_encode() function frequently in the past, I am puzzled by the current issue... Note: Error checking has been omitted for clarity. //PHP <?php session_start(); require 'global/query.php'; $sql = "SELECT sfl,statio ...

Refine your search with Angular filter for nested properties

Trying to implement a filter on a specific element within my JSON object. The filter works effectively, but when I remove it, the properties without the specified sub element are not shown. Any suggestions on how to overcome this issue? Important note: ...

Papaparse and vfile not functioning properly - Output appears jumbled

I recently posted a question on Stack Overflow about parsing large CSV files, the issue can be found here. The problem involves reading a CSV file and converting it into a table format. I attempted to use the code provided in one of the responses, but unfo ...

Issue with extended waiting times in polling

I am currently working on a chatroom using the long poll method. However, I'm facing an issue where every time a long poll occurs and I refresh the page in Chrome or try to send another async request, everything times out. This means I can't load ...

What is the best method for dynamically increasing the data in a shopping cart?

My goal is to stack cart items dynamically every time the addProduct() function is called. I've successfully captured the data, but I'm facing an issue where the quantity always remains at 1 on each function call. Here's the logic I've ...

How can I restrict the draggable space? It is only working on the top and left sides, but I want to disable it on the right and bottom

Attempting to prevent the draggable items from overflowing beyond the body. Succeeded in limiting movement on the top and left sides. Encountering difficulty restricting motion on the right side and bottom. e.pageX -= e.offsetX; e.pageY -= e.offsetY; ...

React Router relies on a DOM for Browser History to function properly

I am currently developing my app using React.js and express. My main focus right now is setting up react-router-dom for the application. Unfortunately, I encountered a warning when attempting to run the app: Invariant Violation: Browser history needs a ...

Enhancing an identity function with type hinting

I am looking to define a specification for a function that returns its input argument, regardless of its type. The crucial aspect here is to mirror the interface of the argument in the return value. For instance, when I type z. on line 6 as shown in the i ...

Transforming Kilobytes Memory Measurements to Megabytes using JSON Path Query Result

I have a query that produces two outputs in two columns: Name Memory The memory output is currently shown in Ki. I want to convert the node memory output to MB when displaying it. How can I modify my JSON path query to achieve this? Here is my current q ...

The Jquery script is ineffective for newly added elements

After creating an Ajax Form that functions well, I noticed that when the result of the form is another form, my script does not work for the new form generated. Is there a way to make the new form function like the old one? $(document).ready(function() ...

Style slipping away when dynamically altering CSS file with JavaScript

My webpage has a style similar to this https://i.sstatic.net/k6TGg.png I am attempting to modify the CSS using JavaScript when a button is clicked. This is my JavaScript code: this.document.getElementById('style-bandle').setAttribute('hre ...

Can new content be incorporated into an existing JSON file using HTML input and the fs.writeFile function?

I recently started learning about node.js and decided to create a comment section that is rendered by the node.js server. I successfully passed the value from a json file into an ejs file, which rendered fine. Now, I have added an input field and submit b ...

Is it possible to convert nested CSS into Material-UI's CSS in JS method?

Here is the code for embedding an iframe: <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: abso ...

Difficulty with AngularJs Translation Partials

I have encountered an issue with binding translation. Some objects are converting to their translated value successfully, while others, as mentioned below, are not working. This problem only occurs the first time I build the project. Upon refreshing, every ...