My array contains a list, and I need to determine how to ensure that a specific element is displayed first based on a condition in the mapping

Here is the object.

 let newObj = {
    firstValue:"abc",
    content:[
      {
        "value": "123",
        "checked": true
      },
      {
        "value": "456",
        "checked": false
      },
      {
        "value": "789",
        "checked": true
      }
    ]
}

In this firstValue is abc so while mapping abc should come first like this:

 let newObj = {
firstValue:"abc",
content:[
  {
    "value": "abc",
    "checked": true
  },
  {
    "value": "123",
    "checked": false
  },
  {
    "value": "789",
    "checked": true
  }
]
}

To achieve this using javascript, you can use a function to rearrange the objects in the array based on the value of 'firstValue' property.

Hope this helps!

Answer №1

let obj = {
  mainValue: "abc",
  data: [
    {
      val: "def",
      enabled: true,
    },
    {
      val: "ghi",
      enabled: false,
    },
    {
      val: "jkl",
      enabled: true,
    },
  ],
};
const position = obj.data.findIndex((item) => item.val === obj.mainValue);
if (position !== -1 && position !== 0) {
  obj.data.unshift(...obj.data.splice(position, 1));
}

Answer №2

Seems like you're interested in arranging the matching object at the top.

You have a couple of options to achieve this. One way is to utilize Array#sort(), but keep in mind that this will modify the original object, so consider cloning it before sorting if needed.

var arr = { firstValue: 'xyz', content: [ { value: 'abc', checked: true, }, { value: 'xyz', checked: false, }, { value: 'lmn', checked: true, }, ], };

const sorted = [...arr.content].sort((a, b) => 
  (b.value === arr.firstValue) - (a.value === arr.firstValue));

console.log(sorted);

Alternatively, you can identify the index of the object using Array#findIndex(), then use Array#splice() and Array#unshift() to move it to the front of the array. To avoid mutating the original array, create a utility function that returns a copy with the desired changes.

var arr = { firstValue: 'xyz', content: [ { value: 'abc', checked: true, }, { value: 'xyz', checked: false, }, { value: 'lmn', checked: true, }, ], };

const orderFirst = (a) => {
  const res = [...a];
  const i = a.findIndex((o) => o.value === arr.firstValue);
  
  if (i && i !== -1) {
    res.unshift(res.splice(i, 1));
  }

  return res;
};

const sorted = orderFirst(arr.content);

console.log(sorted);

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

The GraphQL Resolver function that returns an object

When querying with GraphQL, I receive results in the following format: { "data": { "events": [ { "_id": "65f0653eb454c315ad62b416", "name": "Event name", " ...

How can I call a Vue component method from a different application?

I'm facing an issue where my code works perfectly in pure html/javascript, but not when using vuejs. The function causing the problem is called myMethod(). While debugging in the javascript console, I can access it using myMethod("toto"). However, in ...

Is there an improved method for toggling animations in CSS using jQuery compared to my current approach?

Looking to create a toggle effect for a dropdown box that appears and disappears when a button is clicked. var clickState = false; $("#show").on("click", function() { if (!clickState) { $(".animated").removeClass("off"); refreshElement($(".an ...

"Utilize the most recent version of Uploadify to easily upload your

I am having trouble uploading a video using the latest version of uploadify. Here is my code: HTML: <form enctype="multipart/form-data" class="form-part" action="form.php" method="post"> <input class="uplodify" id="file_upload" type="file"/ ...

The Stepper StepIconComponent prop in MUI is experiencing issues when trying to render styles from the styles object, leading to crashes in the app

Struggling to find a way to apply the styles for the stepper component without using inline styles. I attempted to replicate Material UI's demo, but encountered an error. The code from Material UI's demo that I want to mimic is shown below: http ...

Expanding the outer div with Jquery's append() function to accommodate the inner div elements perfectly

I am facing an issue where my outer div does not expand automatically to fit the elements I append inside it using jQuery. The structure of my div is as follows: <div class="well" id='expand'> <div class="container"> < ...

Removing an element from an array in a Laravel database using AngularJS

I am currently working on a project where I need to delete an item from my Laravel database, which is a simple Todo-List application. To achieve this, I have implemented a TodosController in my main.js file using AngularJS and created a Rest API to connect ...

What causes TypeScript's ReadonlyArrays to become mutable once they are transpiled to JavaScript?

Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement: TypeScript includes a special t ...

Creating dynamic routes in express to enable flexible and customizable paths

Exploring the dynamic usage of paths in Express has been on my mind. Specifically, I have been employing lodash to locate a path in a separate file using regex methods. routes.js const json = require('./routes.json') const _ = require('l ...

Implementing fetch within a custom hook to display a loader within a return function

customFetch hook: import React, { useState, useEffect } from 'react'; const customFetch = (url, options) => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); useEffect(() => { (async () ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

Breaking down a intricate JavaScript expression in order to reformat it into a different structure

As I explore the task of refactoring a legacy application, I find myself faced with complex JavaScript expressions stored in a database column. These expressions contain validation and conditional rendering logic that need to be translated into structured ...

Matching with Regex beyond the limits

Trying to extract a body tag using regex and then replace it with an appended string. However, encountering an issue where the regex is selecting more content than intended. regex: /<body.*[^>]>/i test string: <bla bla ><body class=&apo ...

Enhance your data by modifying and updating objects within an array with Mongoose

I am new to the world of MongoDB, specifically using mongoose for defining my schema. I have encountered a roadblock while trying to update or modify a nested array within my schema and could really use some guidance on how to proceed. Let me showcase my ...

What are the steps to modify the authorization header of an HTTP GET request sent from a hyperlink <a href> element?

I have a unique Angular application that securely saves JWT tokens in localstorage for authentication purposes. Now, I am eager to explore how to extract this JWT token and embed it into an HTTP GET request that opens up as a fresh web page instead of disp ...

Utilizing the each() method to cycle through multiple unordered lists and concealing any nested list items exceeding a count of 8

Struggling to figure out how to loop through all ul elements with a class of ul.children and hide any child elements under ul.child that exceed 8. See the snippet of code below for reference: $(function() { $('ul.children').each(function() { ...

Transform an object in javascript to HTML format

Looking for a function to convert a JavaScript object of this type: {node: 'X', children: [{node: 'Y'}]} into a string resembling HTML. For instance, the example above should be transformed to something like: '<div class="X ...

The jQuery gallery is experiencing some functionality issues

Having an issue with the gallery on my website (currently on my computer, not yet uploaded to a server). Here is the script for the gallery (loaded from the server using PHP): $(document).ready(function() { $('.gallery').hide(); $(' ...

Creating a modal form with jQuery in ASP.NET

I'm fairly new to ASP.NET development and have been able to work on simple tasks so far. However, I now have a more complex requirement that I'm struggling with. My goal is to create a modal form that pops up when a button is clicked in order to ...

Conceal an element along with its space, then signal the application to show alternative content using React

Greetings everyone! I seek assistance with a React Application that I am currently developing. As a newcomer to the Javascript world, I apologize if my inquiry seems trivial. The application comprises of two main elements: a loader, implemented as a React ...