Is there a way to sort through objects in a JSON file using two shared values? Specifically, I'm looking to filter the JSON objects based on both common x and y values

Given a JSON file, I am looking to group objects based on common x and y values. Essentially, I want to group together objects that share the same x and y properties. Here is an example of the JSON data:

let data = [{
"x": "0",
"y": "0",
"k": "0"
},
{
"x": "0",
"y": "0",
"k": "1"
},
{
"x": "1",
"y": "2",
"k": "0"
},
{
"x": "1",
"y": "2",
"k": "5"
},
{
"x": "2",
"y": "2",
"k": "10"
},
{
"x": "1",
"y": "2",
"k": "12"
}
]

The desired result would be as follows:

result = [
[{
"x": "0",
"y": "0",
"k": "0"
},
{
"x": "0",
"y": "0",
"k": "1"
}],
[
{
"x": "1",
"y": "2",
"k": "0"
},
{
"x": "1",
"y": "2",
"k": "5"
},
{
"x": "1",
"y": "2",
"k": "12"
}
],
[{
"x": "2",
"y": "2",
"k": "10"
}]
]

I only need to separate the objects with common x and y, how can I go about solving this issue?

Answer №1

You might want to consider implementing something along these lines:

// Assume that a specific character like "-" does not appear in x / y
const groupA = {};
data.forEach((item) => {
  const key = `${item.x}-${item.y}`;
  groupA[key] = [];
  groupA[key].push(item);
});

const resultA = Object.values(groupA);

// If there is no guaranteed separator
const groupB = {};
data.forEach((item) => {
  groupB[item.x] = groupB[item.x] || {};
  groupB[item.x][item.y] = groupB[item.x][item.y] || [];
  groupB[item.x][item.y].push(item);
});

const resultB = Object.values(groupB).map(item => Object.values(item)).flat();

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

Looking for a way to update a world map image by selecting multiple checkboxes to apply a flood fill color to different countries using Mogrify

Exploring different methods to achieve my goal, I am wondering if creating a web service where users can track visited countries on a world map can be done in a simpler way than using Javascript or Ajax. The idea is for users to mark the countries they hav ...

TypeScript struggling to recognize specified types when using a type that encompasses various types

I have a defined type structure that looks like this: export type MediaProps = ImageMediaProps | OembedProps; Following that, the types it references are defined as shown below: type SharedMediaProps = { /** Type of media */ type: "image" | "oembed"; ...

Enter text into a field on a different webpage and verify if the output matches the expected result

Possible Duplicate: Exploring ways to bypass the same-origin policy I'm facing a scenario where I have a form on my website that requires validation of a number. The validation process involves checking this number against another website where e ...

Tips for Keeping a Responsive Image at the Forefront of a Text-Image Layout as You Scroll

I'm currently in the process of creating a website where text appears on the left side with an accompanying image on the right. The challenge I'm encountering is ensuring that as users scroll, the image adjusts dynamically based on the associated ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

Having trouble uploading an image to AWS using Angular and NodeJS?

I am currently working on a Node/Express application and I need to gather file information for uploading from an Angular/Ionic front end. To achieve this, I have created a separate Service in Angular that successfully retrieves the Image name. However, my ...

Is it possible for the req.url path in expressjs to represent a different URL?

Recently, I discovered some suspicious requests being sent to my node-express server. In response, I created a middleware to record the request URLs. After logging these requests, I noticed that most of them started with '/', but there were also ...

Transfer JSON data from a web URL straight into couchDB using cURL

Is there a way to directly insert JSON data obtained from a curl -X GET command into a couchDB database? For example, is it possible to achieve the following: >>> curl -X GET -H "some_header" http://some_web_JSON -X POST http://127.0.0.1:port/so ...

Evaluate the advancement of a test using a promise notification for $httpBackend

I am currently utilizing a file upload feature from https://github.com/danialfarid/angular-file-upload in my project. This library includes a progress method that is triggered when the xhr request receives the progress event. Here is an excerpt from the so ...

Having difficulty implementing pagination functionality when web scraping using NodeJS

Currently, I am creating a script that scrapes data from public directories and saves it to a CSV file. However, I am encountering difficulties when trying to automate the pagination process. The source code I am using includes: const rp = require(' ...

Is there a way to exclude specific fields from a JSON file when filtering it?

Currently, I am working on a project that requires the use of my Google Maps Location History Json file (obtained via google takeout). The issue I am facing is that this json contains over a million location objects with certain fields, like "activity", wh ...

Having trouble with ejs.filters?

I'm having trouble grasping ejs filters and getting them to work correctly: Server.js var ejs = require('ejs'); ejs.filters.example = function() { //placeholder for example }; Routes.js app.get('/home', function(req, res) { ...

issue with logging in, token verification failed

My current project involves creating a login system with authorization, but for some reason the token is not being transferred properly. const path = require('path'); const express = require('express'); const bodyParser = require(' ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Building User-Friendly Tabs with Twitter Bootstrap: Add or Remove Tabs and Content on the Fly

Looking forward to any assistance or suggestions... I am utilizing Twitter Bootstrap tabs for organizing information on a form page. Each tab will contain a "contact form" where users can add multiple contacts before submitting the entire form. <div c ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

Store JSON data in a Python variable

I need to store data from a Json file into separate variables so that I can use them for other purposes. I have successfully created a Json file from inputs in another QDialog. Now, my goal is to extract the inputs from the Json file and assign them to ind ...

Guide on transforming data into the preferred format and saving it to a file using Python and Apache Beam

My dataset consists of a .ndjson file structured like this: {"property_id": "107", ...} {"property_id": "108", ...} {"property_id": "109", ...} Using Apache Beam, I grouped the data by property_i ...

Exploring data visualization and time zones with highcharts on a React platform

I am working on a chart component in React that is populated with data from an API. The array of objects I receive contains rows structured like this: Rows: [ { EffectiveTime: "06-Nov-2020 00:00:00", FieldName: "GEN_EXP", Re ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...