Tips for extracting a specific attribute from an array of objects using both react and JavaScript while considering various conditions

I have a set of objects structured like this:

const obj_arr = [
    {
        id: '1',
        jobs: [
            {
                completed: false,
                id: '11',
                run: {
                    id: '6',
                    type: 'type1',
                },
            },
            {
                 completed: true,
                 id: '14',
                 run: {
                     id: '17',
                     type: 'type1',
                 },

             },
             {
                 completed: false,
                 id: '12',
                 run: {
                     id: '7',
                     type: 'type2',
                 },
             },
         ],
     },
     {
         id: '2',
         jobs: [
             {
                 completed: true,
                 id: '13',
                 run: {
                     id: '8',
                     type: 'type2',
                 },
             },
             {
                 completed: true,
                 id: '16',
                 run: {
                     id: '9',
                     type: 'type1',
                 },

             }, 
             {
                 completed: true,
                 id: '61',
                 run: {
                     id: '19',
                     type: 'type1',
                 },
             },
         ],
     },
     {
         id: '3',
         jobs: [
             {
                 completed: false,
                 id: '111',
                 run: {
                     id: '62',
                     type: 'type1',
                 },
             },
         ],
     },
 ],

and an arr_ids = ["1","2"]

Now, I need to extract and filter out the ids from obj_arr based on arr_ids, which can be done as follows:

const filteredIds = obj_arr.filter(obj => arr_ids.includes(obj.id));


So the filtered_objarr = [
     {
         id: '1',
         jobs: [
             {
                 completed: false,
                 id: '11',
                 run: {
                     id: '6',
                     type: 'type1',
                 },
             },
             {
                 completed: true,
                 id: '14',
                 run: {
                     id: '17',
                     type: 'type1',
                 },

             },
             {
                 completed: false,
                 id: '12',
                 run: {
                     id: '7',
                     type: 'type2',
                 },
             },
         ],
     },
     {
         id: '2',
         jobs: [
             {
                 completed: true,
                 id: '13',
                 run: {
                     id: '8',
                     type: 'type2',
                 },
             },
             {
                 completed: true,
                 id: '16',
                 run: {
                     id: '9',
                     type: 'type1',
                 },

             }, 
             {
                 completed: true,
                 id: '61',
                 run: {
                     id: '19',
                     type: 'type1',
                 },
             },
         ],
     },  
     ]

Next step is to identify the ids from filtered_objarr where runs are of type "type1" and none of the jobs are marked as completed: false.

Hence, the expected output from filtered_objarr should be "2".

In the given example, the id "1" is omitted because it contains jobs with both completed: true and completed: false for type "type1".

What I've attempted so far?

const output = filtered_objarr.map(obj => obj.jobs.map(job => job.run.type === 
"type1" && job.completed === true));
        

Upon logging the output, it returns:

[ 
    [false,true,false],
    [true,true,true]
]

This approach doesn't provide me with the id of the object that has a job run of type "type1" with no incomplete jobs. How can I achieve that? Any assistance would be greatly appreciated as I am new to programming and still learning. Thank you.

Answer №1

Utilize the Array.filter() method on arrObj to filter by arrIds, and then further refine the filtering process for the jobs array within the previous filter. This involves selecting jobs with a type of type1, and subsequently verifying if the filtered jobs have been completed (true). If they have, return true; otherwise, return false.

const arrObj = [
  {
    id: '1',
    jobs: [
      {
        completed: false,
        id: '11',
        run: {
          id: '6',
          type: 'type1',
        },
      },
      {
        completed: true,
        id: '14',
        run: {
          id: '17',
          type: 'type1',
        },

      },
      {
        completed: false,
        id: '12',
        run: {
          id: '7',
          type: 'type2',
        },
      },
    ],
  },
  {
    id: '2',
    jobs: [
      {
        completed: true,
        id: '13',
        run: {
          id: '8',
          type: 'type2',
        },
      },
      {
        completed: true,
        id: '16',
        run: {
          id: '9',
          type: 'type1',
        },

      },
      {
        completed: true,
        id: '61',
        run: {
          id: '19',
          type: 'type1',
        },
      },
    ],
  },
  {
    id: '3',
    jobs: [
      {
        completed: false,
        id: '111',
        run: {
          id: '62',
          type: 'type1',
        },
      },
    ],
  },
];

const arrIds = ["1", "2"];

const filteredIds = arrObj.filter(obj => {
  if (arrIds.includes(obj.id)) {
    const jobs = obj.jobs.filter(job => job.run.type === "type1");
    if (jobs.length > 0) {
      return jobs.every(job => job.completed === true);
    }
    return false;
  }
  return false;
});

console.log(filteredIds);

Answer №2

In this illustration, the code snippet loops through the data array using a basic for...of loop and employs every method to verify specific requirements.

const data=[{id:"1",jobs:[{completed:false,id:"11",run:{id:"6",type:"type1"}},{completed:true,id:"14",run:{id:"17",type:"type1"}},{completed:false,id:"12",run:{id:"7",type:"type2"}}]},{id:"2",jobs:[{completed:true,id:"13",run:{id:"8",type:"type2"}},{completed:true,id:"16",run:{id:"9",type:"type1"}},{completed:true,id:"61",run:{id:"19",type:"type1"}}]}];

let out = [];

for (let obj of data) {

  // Determine if all jobs with type1 are completed...
  const runCompleted = obj.jobs.every(job => {
    return job.completed && job.run.type === 'type1';
  });

  // Add the id to the output array if not all jobs are completed
  if (!runCompleted) out.push(obj.id);
}

// Analyze the length of the output array
console.log(out);
console.log(out.length);

Answer №3

Here is a simplified version that only requires one iteration:

const filteredOutput = arr_obj.filter(obj => {
    let hasType1 = false;
    return (
        arr_ids.includes(obj.id) &&
        obj.jobs.every(job => {
            if (job.run.type === 'type1') hasType1 = true;
            return job.completed === true;
        }) &&
        hasType1
    );
});

If you just need to check for completeness on type1 jobs, you can use this code snippet:

const filteredOutput = arr_obj.filter(obj => {
    let hasType1 = false;
    return (
        arr_ids.includes(obj.id) &&
        obj.jobs.every(job => {
            if (job.run.type === 'type1') {
                hasType1 = true;
                return job.completed === true;
            }
            return true;
        }) &&
        hasType1
    );
});

Answer №4

Here is a solution :

const filteredArr = arr_obj.reduce((result, item) => {
    const conditionMet = arr_ids.includes(item.id) && item.jobs.every(job => job.completed) && item.jobs.some(job => job.run.type === "type1")
    if (conditionMet) result.push(item.id);
    return result;
}, [])
console.log(filteredArr)

Answer №5

This particular snippet of code effectively addresses the issue at hand, with a strong emphasis on optimization without sacrificing functionality.

const arr=[{id:"1",jobs:[{completed:!1,id:"11",run:{id:"6",type:"type1"}},{completed:!0,id:"14",run:{id:"17",type:"type1"}},{completed:!1,id:"12",run:{id:"7",type:"type2"}}]},{id:"2",jobs:[{completed:!0,id:"13",run:{id:"8",type:"type2"}},{completed:!0,id:"16",run:{id:"9",type:"type1"}},{completed:!0,id:"61",run:{id:"19",type:"type1"}}]},{id:"3",jobs:[{completed:!1,id:"111",run:{id:"62",type:"type1"}}]}];
 
// Optimized data extraction
const targets = ["1", "2"].reduce((a, c) => ({...a, [c]: true}), {})

const result = arr.filter(data => {
  if(targets[data.id]) {
    let containType1 = false
    const jobs = data.jobs
    
    const canSave = jobs.every(job => {
      const isType1 = job.run.type === "type1"
      containType1 = isType1 ? true : containType1
      return isType1 ? job.completed : true
    })
    
    return canSave && containType1
  }
  
  return false
})
 
console.log(result)

Answer №6

Is this solution effective?

const uniqueIds = new Set(idsArray);
const filteredObjects = objectsArray.filter(obj => uniqueIds.has(obj.id));

By using the Set constructor, a set of unique ids is created instead of an array. This allows you to efficiently check if the id property of each object in the objectsArray is present in the "uniqueIds" set.

If you're new to programming, consider exploring the Set and Map data structures along with their related methods. These can be incredibly useful for filtering and merging data when there is a need for uniqueness among elements in an array. In this case, the id serves as a good unique identifier.

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

Creating a seamless integration between a multi-step form in React and React Router

I've been learning how to use React + ReactRouter in order to create a multi-step form. After getting the example working from this link: , I encountered an issue. The problem with the example is that it doesn't utilize ReactRouter, causing the ...

Could my object exports be the issue? I'm new to JS and struggling to figure out why my test is not passing

Just dipping my toes into the world of Javascript and currently tackling objects and test driven development in my classes. I've encountered a bit of trouble with my code and tests - not quite sure why they're failing. Initially, everything work ...

Tips for retrieving a variable from a $.getJSON function

My question is similar to this one: How can I return a variable from a $.getJSON function I have come across several duplicates on Stack Overflow, but none of them provided a satisfactory answer. I understand that $.getJSON runs asynchronously, and I hav ...

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...

Accessing and parsing JSON data from directories within directories

My file directory structure is dynamic, with only the name of $(Root Directory) known at runtime. All folders and files are generated dynamically, with all files being in .json format. I am looking to count the number of files and read the content of eac ...

How can I resolve the "web page not found" error when using jQuery .replace()?

Working on HTML and javascript/jquery scripts, I have encountered a peculiar issue. My script utilizes a for-in loop to iterate through a JavaScript object, substituting specific patterns in HTML-formatted lines with data from the object using jQuery .appe ...

Is Meteor.js the solution for time-triggered server requests?

We are currently in the process of developing an application that matches users from a database every Wednesday and Friday. How can we achieve this using Meteor? In the server code, I am considering organizing this functionality within a timedserver.js fi ...

Using React Hooks and useRef to Retrieve the clientHeight of Dynamically Rendered Images

I'm currently in the process of creating a dynamic image grid and need to determine the exact height of each image in pixels so I can adjust the layout accordingly. However, I've encountered an issue with accessing ref.current.clientHeight as it ...

Leveraging the power of JavaScript and possibly regular expressions to extract numerical values from a

I am attempting to extract a variable number from the text provided in the following example: Buy 5 for € 16.00 each and save 11% Buy 50 for € 15.00 each and save 17% Buy 120 for € 13.00 each and save 28% Buy 1000 for € 10.00 each and save 45% Th ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

Ensuring that two operators are not consecutively placed in a Javascript calculator-validation guide

After creating a basic calculator using HTML, CSS, and JavaScript, I encountered an issue. When validating user input, the calculator currently accepts multiple operators in a row. To address this, I attempted to prevent consecutive operators by checking ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

What is causing my Javascript media query for the sidebar to not function properly?

I am working on implementing a sidebar that slides out 250px using JavaScript on the desktop view. However, I want the sidebar to take up 100% width when viewed on mobile devices. Despite my attempts to use Media Queries in JavaScript to achieve this, I am ...

Collaborate by sharing local storage with other systems

One of my systems (x.x.x.x: 8000) creates a localstorage after logging in. Now, when a user interacts with another system (x.x.x.x: 8001) by clicking a specific button, the information stored in the initial system's localstorage (x.x.x.x: 8000) is nee ...

Invoke function within bxslider callback

I am attempting to utilize a custom function within a bxslider callback, but unfortunately, the function is not being recognized (specifically: Uncaught Reference Error: nextSlideCustom() is not a function) The current code snippet I have is as follows: ...

React: Despite my efforts to return a value from render, nothing was actually returned

My current project involves creating nested components to display the dataset I have. export const MyComponent = (props) => { const groupMilestoneByYear = (data) => { // Take Milestone Data array as input and group it by Year let yearGroup ...

Service workers do not support fetching from .html files

Struggling with creating a functioning service worker for offline use has been a challenge. Despite trying numerous examples, the success has remained elusive. Initially, I suspected that the dynamic nature of my PHP-based website was causing the issue, or ...

Can image data be extracted from a canvas without needing to physically render the canvas?

I am currently working on an Angular application that utilizes Chart.js to create dynamic charts in various views. Additionally, the application has the capability to export data to a PDF format using the PDFMake JavaScript library, which is a basic tool a ...

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...

The ID update functionality in Node.js is malfunctioning

Hello everyone, I am currently venturing into the world of NodeJS with a goal to create a backend API for a car rental agency. After writing some code to update, view, and delete records by id stored in MongoDB, I encountered a strange issue where it only ...