Merge and filter unidentified subsets of objects within an array comprised of multiple objects

a more efficient way to achieve the desired output of this code snippet is by checking if sub array 0 exists, combining it, and then filtering the result based on the key code.

Your assistance is greatly appreciated!

let array = [
  {
    id: 1,
    text: 'stuff1',
    arr0: [
      {id:1, code: 'imacode1'},
      {id:2, code: 'imacode2'},
    ]
  },
  {
    id: 2,
    text: 'stuff2',
    arr0: [
      {id:3, code: 'imacode3'},
      {id:4, code: 'imacode4'},
    ]
  },
  {
    id: 3,
    text: 'stuff3',
    arr0: []
  }
]
let arr = [];

for(let i of array){
  if(i.arr0.length !== 0){
    arr.push(i.arr0)   
  }
}
arr = arr.flat()
for(let j of arr){
  if(j.code === 'imacode2'){
    let code = arr.filter(j=>j.code!=='imacode2')
    code = code.map(({code}) => code)
    console.log(code)
  }
}
    

edit: added code snippet for clarity

Answer №1

To achieve the desired result, you can utilize Array.flatMap() in combination with Array.filter(). Start by using .flatMap() to construct an array that includes all elements from each arr0.

Next, apply .filter() to only retain the specified elements, utilizing a custom filter function that can be adjusted as needed - for instance, excluding any items with a code of 'imacode2'.

let array = [ { id: 1, text: 'stuff1', arr0: [ {id:1, code: 'imacode1'}, {id:2, code: 'imacode2'}, ] }, { id: 2, text: 'stuff2', arr0: [ {id:3, code: 'imacode3'}, {id:4, code: 'imacode4'}, ] }, { id: 3, text: 'stuff3', arr0: [] } ]

// Adjust the filter criteria as needed..
const filterProc = ({id, code}) => code !== 'imacode2';
const result = array.flatMap(el => el.arr0 || []).filter(filterProc).map(({code}) => code);
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Setting up Jest

I'm currently attempting to integrate the Jest Testing framework into my React Native project. Unfortunately, I am encountering an error message: Failed to retrieve mock metadata: /Users/me/Documents/Development/project/node_modules/global/window.js ...

What is the correct way to access a static variable within a non-static method? For example, I am trying to retrieve the value of the maxId variable

public static List<Movie> movies; static { movies = new ArrayList<>(); movies.add(new Movie(1, "Fprd vs Ferrari", "Movie on Racing", "abcd", "xyz")); movies.add(new Movie(2, "F2", "Comedy Movie", "Venkatesh", "Tamanna")); movie ...

The ngModel directive is causing properties to be retrieved twice

I built a simple component for displaying a list of items. Inside the component, I have an ngfor loop that includes checkboxes with [(ngModel)] bindings. Everything seems to be functioning correctly. <div *ngFor="let armor of armorList"> < ...

Utilize the Tab feature effectively in Impress.Js

Currently, I have disabled the Tab key in Impress.js so that it only moves to the next slide. However, when I try to focus on links and delete this code to let it behave normally, Impress.js crashes. Has anyone found a workaround for this issue? Appreciat ...

I am looking to save a query in the form of a JSON object. (Issue: The FOR JSON clause cannot be used in a SELECT INTO statement.)

CREATE TABLE #T ( DateColumn DATE, SomeColA VARCHAR (20), Temp INT, Attribute1 VARCHAR (10), Attribute2 VARCHAR (10) ) INSERT INTO #T VALUES ('20180101', 'A', 8, 'D', NULL) INSERT INTO #T VALUES ('20180 ...

Working with multi-line HTML content within Javascript

I am currently using JavaScript to define the behavior of a button on a website. I want the button to add new HTML content to a specific part of the page, and I would like to use the MVC extension method Html.EditorFor to create this new HTML. Here is wha ...

What is the process for incorporating a resource into a bundle with the fhirclient library (Smart on FHIR)?

Recently, I've been utilizing the fhirclient (Smart on FHIR) python library to work with bundles and individual resources. However, I'm facing a challenge in figuring out how to add a resource to a bundle using helper methods within the "Bundle" ...

Having difficulties implementing horizontal scrolling for the Tabs component in Material UI

I can't seem to enable horizontal scrolling for the Tabs in material UI. Here is the version of Material UI I am using: As the number of Tabs increases, they are becoming wider. I tried to set the width, but it ends up affecting the entire Tabs tab ...

I'm stumped trying to identify the issue in the JavaScript code provided. I attempted to save a function within a variable with no success

After incorporating the suggestions I received, I have revised the entire code. However, there seems to be a missing element as I am still unable to utilize the var deducere in mathematical operations. I consistently receive NaN. Any advice or feedback o ...

What methods can I use to implement phone number validation in Ionic 2?

Looking to implement phone number validation in ionic 2, I came across an example on intlpnIonic which was designed for ionic 1. However, I want to achieve something similar to the image provided here: https://i.sstatic.net/qqSak.png My Query : How can I ...

Tips for using JSON.stringify in a secure manner

After receiving a JSON object, I convert it to a variable called embed. The console.log output is: console.log(send_me_along) {"provider_url":"https://www.site.com/","description":"Stuff, you’ll need to blah blah","title":"Person detail view & ...

Tips on securely saving passwords using Greasemonkey

Created a custom userscript that prompts users to save their login credentials in order to avoid entering them repeatedly. Familiar with using localStorage.setItem() to store key-value pairs, but concerned about storing passwords in clear text. Seeking ad ...

The server cannot process the content type 'application/json;charset=UTF-8' as it is not supported

As a newcomer to the Spring World, I am venturing into my first Jquery journey. I am attempting to retrieve JSON data from a JSP page using an Ajax call to the controller. Unfortunately, I encountered an error: org.springframework.web.HttpMediaTypeNotSuppo ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

How to locate the index of a specific item or multiple items within a JsonArray?

Can you help me determine which city is closest to Vancouver: Victoria, Washington or Texas? Once I find the shortest distance, how can I identify which destination address this value corresponds to? { "destination_addresses" : [ "Victoria, BC, C ...

Retrieving just the initial character from each element in the array

I need assistance to understand why I am only getting the first character of each array element when inserting into the database. The data is sourced from checkboxes and once submitted, it looks like this: array ( 0 => 'Water Sealed', 1 => ...

Improve performance by rendering table rows without using binding techniques

My current project involves using Angular 1.4, where I have encountered performance challenges with ng-repeat while rendering a large number of rows, such as for tables. I am curious if there is an efficient way to use ng-repeat or explore different iterat ...

Deleting Images of Specific Width and Height

Having set up a system to automatically upload image posts to my WordPress site from Reddit using IFTTT.com, I am now facing an issue. Some of the posts do not have images and I would like them to be removed automatically. Upon visiting the site, you will ...

What will occur if I invoke response.end in Node.js while asynchronous I/O operations and callbacks are still executing?

When working with Node.js, what happens if you call "response.end()" while I/O calls and/or callbacks are still being executed? Take a look at the code snippet below: var app = http.createServer(function(request, response) { response.writeHead(200, { ...

What is the best way to retrieve a value from within the callback function while working in the global scope

While working with express Js, I encountered a situation where I needed to export the port on which the server is running for testing purposes. However, I found that the port value is only accessible within the callback function of app.listen. Is there a ...