Discovering the dissimilarity between two nested arrays containing objects by comparing their OBJECTID values

Struggling to figure out how to filter a nested Object array based on the OBJECTID. I understand filtering arrays with strings/numbers, but this example is more relevant to what I am working on.

let geojson = [
  {properties: {OBJECTID: 6249646, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, 
  {properties: {OBJECTID: 6249646, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}, 
  {properties: {OBJECTID: 6249647, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
  {properties: {OBJECTID: 6249647, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
  {properties: {OBJECTID: 6249648, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
  {properties: {OBJECTID: 6249649, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}} 
  ]


let newjson = [
  {properties: {OBJECTID: 6249647, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
  {properties: {OBJECTID: 6249648, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
  {properties: {OBJECTID: 6249649, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
  {properties: {OBJECTID: 6249650, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
  {properties: {OBJECTID: 6249651, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}
  ]

Desired Outcome: [
    {properties: {OBJECTID: 6249650, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}},
    {properties: {OBJECTID: 6249651, FeatureCode: 10185, Version: 3, VersionDate: "1/25/2018"}}
  ]

This code snippet is just a portion of my actual code. Attempted using a for loop to check OBJECTIDs, but encountered infinite loops resulting in crashing. Any assistance would be greatly appreciated!

Answer №1

geojson.filter( obj => obj.properties.ID == 1 || obj.properties.ID == 2)

Have you considered utilizing the filter method?

Here's why it can be beneficial: Instead of having to manually loop through an array and check conditions, you can simply return true or false within the filter method. This function will automatically iterate over each element in the array.

If you're working with a larger array, you could implement something like this:

fil=[1,2,4];
geojson.filter( obj => fil.indexOf(obj.properties.ID) !== -1)

Answer №2

If you're facing issues with the code snippet below, perhaps it can provide some insights. Although, I'm uncertain why it's not functioning as anticipated.

let geojson = [{properties: {ID: 1}, name: "Jimmy"}, 
               {properties: {ID: 2}, name: "Joe"}, 
               {properties: {ID: 3}, name: "Ji"}, 
               {properties: {ID: 4}, name: "my"}]


let test = [{properties: {ID: 3}, name: "Ji"}, {properties: {ID: 4}, name: "my"}]

var mappedTestArray = test.map(testObject => {
    return testObject.properties
})

console.log(mappedTestArray)

let geoJson = geojson.filter(geoObject => {
    console.log(geoObject.properties)
    console.log(mappedTestArray.includes(geoObject.properties))
   return mappedTestArray.some(el => el === geoObject.properties)
})

console.log(geoJson)

Answer №3

If you're looking to retrieve specific objects from an array based on multiple values, here's a straightforward solution:

const selectedIDs = [1,2,3, ...];

const selectedObjects = geojson.filter(item => selectedIDs.includes(item.properties.ID));

Answer №4

1) Assemble the ids into a test_ids array that requires filtering.
2) Apply the filter function to the geojson array and verify if it is not part of the previously mentioned array.

let geojson = [
  { properties: { ID: 1 }, name: "Jimmy" },
  { properties: { ID: 2 }, name: "Joe" },
  { properties: { ID: 3 }, name: "Ji" },
  { properties: { ID: 4 }, name: "my" }
];

let test = [
  { properties: { ID: 3 }, name: "Ji" },
  { properties: { ID: 4 }, name: "my" }
];

const test_ids = test.map(x => x.properties.ID);

const res = geojson.filter(gj => !test_ids.includes(gj.properties.ID));

console.log(res);

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

What is the best way to convert a string to an integer in JavaScript while still maintaining compatibility with Internet Explorer 11?

Here is the code snippet that I am working with: setCol (param) { // missing forEach on NodeList for IE11 if (window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; } const a ...

Why does my camera suddenly switch to a rear-facing view when I begin my Zoom meeting?

I am facing an issue with my camera function where it initially starts off facing backwards, but as soon as I perform the first scroll, it flips around and works correctly. Please note that I am a beginner in coding. Kindly be aware that there is addition ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

Is it possible to arrange data at the server without using a query?

Having some trouble with sorting my array before printing it in handlebars. My app is built using expressjs, handlebars, mongoose/mongodb and I can't seem to figure out the best approach. app.js (entry point) var debug = require('debug'); ...

How can I prevent all AJAX/Websocket data requests on a webpage?

I have a webpage that loads multiple Ajax and WebSocket requests once the page is fully loaded. This happens because of the frequent updates to the chatroom and chart prices on the page. Is there a way to prevent the browser from fetching the chatbox data ...

Ensure that AJAX callbacks function properly within a loop

Why is the success call only working for the first response in this code? for(i = 1; i <= 6; i++) { $.ajax({ url : 'runTest.php', type : 'post', data : "testNumber="+i+"&url=" + testUrl, data ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

Empower the user with the ability to interact through touch on dynamically

I am trying to make a div touchable and draggable. I have dynamically created 1 to 10 divs within another div. Currently, these divs can only be dragged using the mouse or cursor. However, I want to enable dragging through touch as well. Can anyone provi ...

Executing two SQL queries simultaneously in NodeJS can be achieved by using a single statement

app.get("/total", function(req,res){ var q = "SELECT COUNT(*) AS new FROM voters_detail WHERE parties LIKE '%BJP%'"; connection.query(q, function(err, results){ if(err) throw err; var hello = results[0].new; res.send("BJP Was Voted By ...

"Encountering a hiccup with AngularJS and Spring MVC: Error 400 - Bad

My attempt to post an object containing an ID (integer) and an array is resulting in a HTTP 400 Bad request response from the server side. Here's what I have so far... Java Bean Object for Request: public class GuardarVentaRequest { private Integer ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

Merging two arrays together

I have 2 arrays: $ping_array = array(); $ping_array[] = '400'; $ping_array[] = '200'; $ping_array[] = '600'; $ping_array[] = '100'; $timestamp_array = array(); $timestamp_array[] = '2013-03-25 16 ...

Exploring the array pushing functionality in MongoDB

I have received a MongoDB query outputting two fields (110, 1; 105, 1; 105, 2). My goal is to store these results in an array for use in a while loop: 110, 1 105, 1 105, 2 I have attempted to create a function for this task, but my array remains empty: ...

"Sending a file (Image) through NextJS API Routes to an external API: A step-by-step guide

I am currently using a combination of NextJS (SSR and SPA for authorized dashboard) with Django Rest FW on the backend. To handle authentication, I employ JWT tokens stored in cookies. As a result, it is necessary to have a middleware at /pages/api/* that ...

"Import data from a text file and store it as an array of objects using Types

I need assistance with converting the information in my text file into an array of objects. Below is a snippet of the data from the text file: DOCNO NETAMOUNT IREF1 IREF2 DOCDT 001 30000 50 100 6/7/2020 2 40000 40 90 6/7/2020 Currently, t ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

Update ngx-datatable when the user clicks on a different directive

My issue involves a Side Navigation with a docking feature and a data table in the Main View. When I undock the side navigation, the data table does not recalculate automatically, leaving empty space where the Side Navigation was. This requires me to manua ...

"Identifying Mouse Inactivity in React: A Guide to Detecting When the Mouse

I need to dynamically control the visibility of a button element based on mouse movement. I am able to show the button when the mouse is moving using onMouseMove, but I'm stuck on how to hide it when the mouse stops moving. React doesn't have an ...

Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting ...