retrieve items from an array according to the hierarchy of the objects

I am working with an array of objects that looks like this:

let obj = [
  { name: "Qwerty1", status: "Development" },
  { name: "Qwerty2", status: "Development" },
  { name: "Qwerty3", status: "Staging" },
  { name: "Qwerty4", status: "Production" },
  { name: "Qwerty5", status: "Production" }
]

In need of creating a function

getList(status) {

}

When calling this function, I will specify a status parameter such as "Development", "Stating", or "Production"

If I input "Production" to this function, it is expected to return an array containing all the objects with status: "Production", along with objects having statuses "Staging" and "Development"

For "Staging" status, the function should provide an array including all objects marked as "Staging" as well as those labeled "Development"

If given "Development" as the status, only objects with "Development" status must be returned

The order of priority is Production -> Staging -> Development ("Production" includes "Staging", "Staging" includes "Development")

Please keep in mind that the object cannot be altered as it originates from an API.

Answer №1

Straightforward yet clear:

function checkStatus(status) {
    if (status === 'C') {
        return result
    }
    if (status === 'B') {
        return result.filter(item => item.status === 'B' || item.status === 'A')
    }
    if (status === 'A') {
        return result.filter(item => item.status === 'A')
    }
}

Answer №2

Locate the final occurrence of a matching Status, and then use slice to extract the elements from index 0 to that position:

let obj = [
  { name: "Qwerty1", status: "Development" },
  { name: "Qwerty2", status: "Development" },
  { name: "Qwerty3", status: "Staging" },
  { name: "Qwerty4", status: "Production" },
  { name: "Qwerty5", status: "Production" }
]

function getList(status) {
  let lastIndex;
  for (let i = obj.length - 1; i >= 0; i--) {
    if (obj[i].status === status) {
      lastIndex = i;
      break;
    }
  }
  if (lastIndex === undefined) {
    return [];
  }
  return obj.slice(0, lastIndex + 1);
}
console.log(getList('Development'));
console.log(getList('Staging'));
console.log(getList('Production'));

Answer №3

Utilize the Filter method to sort through a list of objects and compare their status with a specified parameter. Establish numerical values for each status by creating a Map that links statuses to values.

const obj = [{"name":"Qwerty1","status":"Development"},{"name":"Qwerty2","status":"Development"},{"name":"Qwerty3","status":"Staging"},{"name":"Qwerty4","status":"Production"},{"name":"Qwerty5","status":"Production"}]

const statusToValue = new Map([['Development', 0], ['Staging', 1], ['Production', 2]])

const getList = (status) => obj.filter(o => statusToValue.get(o.status) <= statusToValue.get(status))

console.log(getList('Development'))      
console.log(getList('Staging'))
console.log(getList('Production'))

Answer №4

One effective method is to utilize the .filter() function

This particular piece of code iterates over the elements in the object, establishes the order, and applies the .filter() function to verify if the current item falls below the specified status parameter within the hierarchy.

let obj = [
  { name: "Qwerty1", status: "Development" },
  { name: "Qwerty2", status: "Development" },
  { name: "Qwerty3", status: "Staging" },
  { name: "Qwerty4", status: "Production" },
  { name: "Qwerty5", status: "Production" }
]
let order = [...new Set(obj.map(e => e.status))];

function getList(status) {
  const output = obj.filter(e => order.indexOf(status) >= order.indexOf(e.status));
  return output;
}

console.log(getList("Staging"));

Answer №5

Utilize object literals in order to convert words into numeric values for comparison purposes. By doing this, you can establish the desired order for status levels, regardless of the alphabetical sequence of status names.

let statusLevels = {"Development": 0,  "Staging": 1, "Production": 2};

let obj = [
  { name: "Qwerty1", status: "Development" },
  { name: "Qwerty2", status: "Development" },
  { name: "Qwerty3", status: "Staging" },
  { name: "Qwerty4", status: "Production" },
  { name: "Qwerty5", status: "Production" }
];

function getStatusArr(itemStatus) {
  // compares the status using numerical values based on the object literal
 return  obj.filter(o => statusLevels[o.status] <= statusLevels[itemStatus]);
}

console.log(getStatusArr('Staging'))

// displays all levels up to and including "Staging"
//[
//  {
//    "name": "Qwerty1",
//    "status": "Development"
//  },
//  {
//    "name": "Qwerty2",
//    "status": "Development"
//  },
//  {
//    "name": "Qwerty3",
//    "status": "Staging"
//  }
//]

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

Trouble fetching values from Google Sheets using getBatch method in JavaScript

Using javascript fetch() to retrieve a single value from a Google sheet works perfectly fine for me. However, when attempting to read multiple ranges, I encounter a 403 error. The following code executes without any issues: const apiKey = 'insert-you ...

Ensure that the JSON object exists before saving it to local storage

[ { "id": 1, "title": "my First Item", "body": "" }, { "id": 2, "title": "my Second Item", "body": "" }, { "id": 3, "title": "my Third Item", "body": "" } ] Do ...

The browser prevented the script located at “http://127.0.0.1:5500/assets/platform.png” from loading due to an invalid MIME type of “image/png”

Sorry if this question seems repetitive, but despite extensive searching, I haven't been able to find a solution to my specific problem. I am currently working on developing a basic JavaScript game, but I'm facing challenges when it comes to impo ...

I'm having trouble launching Clinic.js, any suggestions on what steps I should take next?

When starting up your application, use the following command: clinic doctor --on-port 'autocannon -m POST localhost:8000/users/register' -- node dist/main.js If you need help, check out the Clinic.js Doctor - v9.2.0 log. The clinic doctor tool ...

Unintroduced jQuery Keyup

I am currently working on a project where I am trying to incorporate an autocomplete feature into an input form. My approach involves using jQuery to trigger an AJAX call to a servlet and adding a listener on the input field for keyup events. However, it s ...

Custom objects do not return true for Symbol.hasInstance

The TypeScript playground encounters an issue with the Symbol.hasInstance built-in symbol, while it functions properly for other symbols. Testing other symbol methods such as Symbol.match and Symbol.replace show no problems, but Symbol.hasInstance is not ...

Incorporate seamless integration by using the npm install command

I am currently facing an issue where I need to identify and remove unused dependencies from my package.json file every time I run npm install for my app. Is there a method to automatically include the npm package https://www.npmjs.com/package during the n ...

Reveal the array on the frontend in a row each time using Javascript

My array contains the following items: let array=["First", "Second"] I want to display each item on a separate line (without commas), like this: First Second I attempted splitting the array using: let data.split("\n") However, the output was: ...

using hover/click functionality with a group of DIV elements

I have a group of DIV elements that I want to apply an effect to when hovering over them with the mouse. Additionally, when one of the DIVs is clicked, it should maintain the hover effect until another DIV is clicked. <div class="items" id="item1"> ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

The click function for the parent div will not be executed if I click on the child div

Hey, I encountered an issue in my code that I need help with. $(document).ready(function() { $(document).on('click', '.rohit', function() { alert('rohit'); }) $(document).on('click', '.azad', ...

"Exploring the usual progress of a standard GET request using Axios

My Objective: I am utilizing Vue And Axios, with the goal of displaying the progress in percentage on the console. The Challenge: The request itself takes around 4 seconds or more because it fetches a large amount of data, processes it into an excel fil ...

Exploring the capabilities of using XPath with a DOM document

I've been attempting to locate an xml node using an xpath query, but I'm having trouble getting it to work. When I try in Firefox, the result is always "undefined" and Chrome throws an error code. <script type="text/javascript"> var xmlSt ...

Get a specific attribute of an object instead of directly accessing it

Is there a way to retrieve a specific object property in my checkForUrgentEvents method without referencing it directly? I attempted using Object.hasOwnProperty but it didn't work due to the deep nesting of the object. private checkForUrgentEvents(ur ...

Firebase updates are not causing React components to update as expected

I've developed a people tracker for my smart home dashboard using React and Firebase. However, I'm facing an issue where the React component is not re-rendering when there are changes in the Firebase database. I'm unsure where I am making a ...

Guide on how to use Vue's watch feature to monitor a particular property within an array

I am interested in observing the "clientFilter" within an array TableProduit: [ { nr_commande: 0, date_creation: "", id_delegue: "1", clientFilter: "" } ], ...

Creating a unique Nest.js custom decorator to extract parameters directly from the request object

I am working with a custom decorator called Param, where I have a console.log that runs once. How can I modify it to return a fresh value of id on each request similar to what is done in nestjs? @Get('/:id') async findUser ( @Param() id: stri ...

Having issues with jQuery Validate not validating fields when using an onclick handler?

I am looking to implement an onclick event handler for validating form fields using jQuery Validate. Here is the code I have: <input type="text" id="Name" name="Name"> <a class="btn btn-primary js-add-names" href="#">Add Names</a> &l ...

When an element is dragged and dropped into a div, an identifier name will be added to the URL

Hey there! I'm new to this and need some guidance. I want to create a feature where users can drag items from a list and drop them into a container div. Once dropped, the item's ID would be added to the URL so that users can share their selection ...

Using Vue.js, you can set a method to return data directly to

Having just begun my journey with Vue, I find myself in a bit of a predicament. As part of my learning process, I am developing an app for tracking episodes in TV series. The initial step involves searching for series and adding them to a database. When co ...