Refining a JSON array using a preset list of values

Just starting out with typescript in angular 2 and encountering a bit of a challenge. Here's the situation:

needle json 
[{"empId":100,"orgId":500}
{"empId":201,"orgId":566}]

The above json is structured in a specific order, and we need to preserve that order when searching for matching values in another json array (Haystack).

Haystack json array
[
{"empCode":21,"fname":"Ashish","Lname":"Shukla"},
{"empCode":22,"fname":"John","Lname":"Mark"},
{"empCode":21,"fname":"Vigil","Lname":"Rocker"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"},
{"empCode":21,"fname":"Erik","Lname":"Francis"},
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":21,"fname":"Feeder","Lname":"Kapoor"},
{"empCode":21,"fname":"Dan","Lname":"Rox"},
{"empCode":21,"fname":"Herb","Lname":"Deen"},
{"empCode":21,"fname":"Nate","Lname":"Diaz"},
{"empCode":21,"fname":"Nick","Lname":"Diaz"},
{"empCode":21,"fname":"Conor","Lname":"Pussy"}
]

My goal is to extract the values from the haystack array that match the ids in the needle array, while preserving the order specified in the needle.

{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"}

I have a solution in place, but I suspect it may not be the most efficient as it involves multiple loops. Any suggestions for a more optimal approach?

NOTE: It's crucial to maintain the order of employee IDs in the result json as per the needle json.

Thank you very much :)

Answer №1

Here is the solution

let needle: any;
let hayStack: any;

needle = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
];

hayStack = [
{"id": 1, "firstName": "John", "lastName": "Doe"},
{"id": 2, "firstName": "Jane", "lastName": "Smith"},
{"id": 3, "firstName": "Tom", "lastName": "Jones"}
];

const needleIds = needle.map(item => item.id);
const haystackIds = hayStack.map(item => item.id);

const result = haystackIds.map((id, index) => {
if (needleIds.indexOf(id) != -1) {
  return hayStack[index];
}
}).sort().filter(item => (item != undefined));

console.log(result);

Final Result

0:{id: 1, firstName: "John", lastName: "Doe"}

1:{id: 2, firstName: "Jane", lastName: "Smith"}

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

How to send data to an external API using Dart methods and parameters

I would like to send data to my web service using Flutter Dart JSON within my API link. How can I achieve this? ...

Encountering circular reference error in JSON serialization with Rails and Mongoid's Geospatial objects

After executing a geolocation query, I have an array of Mongo objects like this: @data = Record.geo_near([lng,lat], :max_distance => dist, :unit => :m, :spherical => true) I am attempting to format the response according to the expected output: ...

Tips for presenting dummy content in an Angular application with HTML

I have created a mock service file and I would like to display it in my HTML, but I'm not quite sure how to make it display correctly. Any help or suggestions would be greatly appreciated. <div class="container2"> <div class=" ...

Developing a custom command-line interface (CLI) with TypeScript and Node.js

I'm eager to develop my custom command-line interface (CLI) using the power of TypeScript and Node.js. Once I have compiled the code with tsc, I proceeded to install it as a global CLI by running npm install -g . However, upon executing test-cli in t ...

Retrieve the elements from the array based on the specified key value

json_data = {"fruits": ["apple", "banana", "orange"],"vegetables":["tomatoe", "cucumber", "potato"]} Is there a way to access the arrays in json_data without needing to use numeric keys? For example: json_data[0][0] #this should return "apple" ...

Modify the variable value only in React when the state undergoes a change

I'm facing a situation where I need to reset the stocksHelper class and instantiate it again whenever the component renders based on a change in the stocks' useState. This is essential because upon a change in stocks, a calculation needs to be pe ...

Serialization of HTML string into JSON format

While working in a Razor View, I encountered the following line: @Html.Raw(Json.Encode(new { tag = "<br />" })); This code snippet replaces HTML tags and generates the response: {"tag":"\u003cbr /\u003e"}; However, my desired output is: ...

Add an image to a directory with Angular 7

I am having trouble uploading an Image to the assets/ folder using Angular 7. Below is my attempted solution: HTML: <form [formGroup]="form" (ngSubmit)="postData()" class="intro-form-css"> <div class="form-row"> ...

Tips for adding JSON values to an object

There is a specific object called SampleObject which has the following structure: { ID: "", Name: "", URL: "", prevName: "", Code: "", } I am looking to insert the values from the JSON object below (values only): var object = { "Sample ...

Sharing data contracts between Asp.Net MVC 2 and client side javascript: Is it possible?

Imagine this scenario: You have an Asp.Net MVC 2 project with object classes that define view models. You serialize these models to the client's web browser using JSON. The client then adds information to the objects, such as an Order Line on an Inv ...

Combining the contents of two JSON Arrays to form a JSONObject in Java

My JSON Arrays are structured like this: [6, 7, 8, 9, 10, 11] [122402538, 12240345, 122496, 122617, 1227473, 1228495] The goal is to merge each Long value with another while preserving its index, resulting in a structure like: [{"id": 6, "timestamp" ...

Extract information from the JSON data provided

In my JSON data, I have a parameter named 'actions' with the following values: 'actions': [{'action_type': 'onsite_conversion.post_save', 'value': '1'}, {'action_type': 'link_clic ...

Creating an efficient and user-friendly ordering system for playlists in Django

Seeking a solution using Django ORM: In my scenario, I have two models: Playlist and Track. The Playlist model includes the "name" field and the Track model contains fields like "name" and "mp3". Additionally, there is a third model called PlaylistTrack w ...

Detecting changes in custom ExceptionHandler may cause delays in recognition

Currently, I am working on integrating a personalized ExceptionHandler in an Angular 2 application that sends unhandled errors to a customized AlertsService. The objective is to enable the main App component to subscribe to the alerts provided by the Alert ...

Iterate through JSON data and access values based on keys using a $.each loop

I have retrieved JSON data from the controller using AJAX and now I want to access this data. The data is in the form of a list of objects (array) with key-value pairs, so I am planning to use .each() function to go through all the data. The array looks li ...

Using the Async feature, I can retrieve the value of a string type when the return type of a function is Promise<any>

While working on a custom pipe, I encountered a situation that puzzled me. Can you explain why the code snippet below is considered valid? async transform(value: any): Promise<string> { let fullNameBasedOnPreference: string; fullNameBasedOnP ...

Deleting a precise key and value from a nested JSON array stored in a PostgreSQL column

I have a PostgreSQL table with a json object field named mytable.fields containing the following data { "a": "1", "b": [ { "c": 2, "d": 3 }, { "c": 4, " ...

Mapping JSON responses to models in Angular 4: A comprehensive guide

I have been struggling to properly map the endpoint response to my model in Angular4 using HttpClient. Despite receiving data from the service, it does not align correctly with my model class. Here is the JSON structure returned by the service: { "re ...

Replace current element in Angular 2

I am looking to change the current element during routing instead of simply adding to it. Below is the code I am currently using: <router-outlet> <div class="=row" style="height:30%"></div> <div class="=row"> <a ...

Transforming a single object into several arrays

I have a JSON file called "icon.json" that contains the following data: [ { "name": "happy", "url": "1.gif" }, { "name": "excited", "url": "2.gif" }, { "name": "surprised", "url": "3.gif" ...