Rearranging information within a JSON structure

Here is a sample of Javascript object and code to consider:

Javascript Object

{
    "thing":{
       "data":"some data",
       "thumb":"some data",
       "data1":"some data",
       "data2":"some data",
       "data3":"some data",
    },
    "extra1":[
       {
          "extradata1":"some data",
          "extradata2":"some data",
          "extradata3":"some data",
          "extradata4":"some data"
       },
       {
          "extradata1":"some data",
          "extradata2":"some data",
          "extradata3":"some data",
          "extradata4":"some data"
       }
    ],
    "extra2":[
       {
          "hightlighted": false, 
          "extradata2":"some data",
       },
       {
          "hightlighted": false, 
          "extradata2":"some data",
       },
       {
          "hightlighted": true, 
          "extradata2":"some data",
       },
       {
          "hightlighted": false, 
          "extradata2":"some data",
       }
     ]
}

The task is to locate an object in 'extra2' where the value is true, remove it from its current position, and insert it back at the beginning of the 'extra2' object.

The solution attempt involves:

for (var i=0; i<object.extra2.length; i++){
        if (object.extra2[i].highlighted === true) {
            highlightStore = object.extra2[i];
            delete object.extra2[i]
            object.extra2.unshift(highlightStore)
        }
    }

However, troubleshooting is needed as the intended functionality is not yet achieved.

Answer №1

The problem lies here:

object.extra2.push(highlightStore)

Instead of using the push() method to add elements to the end of an array, you should utilize the unshift() method which adds elements to the beginning like so:

object.extra2.unshift(highlightStore)

The unshift() method places elements at the start of the array.

Answer №2

It is not recommended to alter the original data directly as it can lead to complications. Avoid using mutating methods such as push or shift.

Instead, consider creating new variables to store modified versions of the original data.

For your specific scenario, a possible solution would be:

const extra2sorted = [ ...data.extra2.filter(v => v.hightlighted), ...data.extra2.filter(v => !v.hightlighted) ]

Answer №3

One way to organize the provided information is by arranging the dataset by utilizing the "hightlighted" characteristic. (Take note of the spelling error. It should actually be "highlighted".) To achieve this, you can follow the example below:

const object = {detail: {info: "some details", image: "some image", data1: "some info", data2: "some info", data3: "some info"}, additionalInfo1: [{extraDetail1: "some detail", extraDetail2: "some detail", extraDetail3: "some detail", extraDetail4: "some detail"}, {extraDetail1: "some detail", extraDetail2: "some detail", extraDetail3: "some detail", extraDetail4: "some detail"}], additionalInfo2: [{hightlighted: false, moreDetail2: "some detail"}, {hightlighted: false, moreDetail2: "some detail"}, {hightlighted: true, moreDetail2: "some detail"}, {hightlighted: false, moreDetail2: "some detail"}]}

object.additionalInfo2.sort(({hightlighted: h1}, {hightlighted: h2}) =>
  (h1 && !h2) ? -1 : (h2 && !h1) ? 1 : 0
)

console.log(object)
.as-console-wrapper {min-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

Using Node.js to retrieve child processes associated with a daemon and terminate them

I am attempting to create a node application that allows me to send the command kill -9 to all child processes of a single daemon. Just to clarify, there is one daemon running on our server. Upon startup, it initiates a process for communicating with clie ...

Having trouble with Vue's $route.push method not working when invoked from a method?

I am currently in the process of creating a search bar for my application using the vue-bootstrap-typeahead autocomplete library. For those unfamiliar, when an option is selected from the suggestions list, it triggers the @hit event which passes the result ...

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...

An ASMX web service encountering an unescaped double quote within a parameter while processing JSON data

Within my HTTP REQUEST, a valid JSON string is present with a double quote in the middle of the name "jo\"hn" escaped. This was captured by Fiddler Web Debugger. {"name":"firstName","value":"jo\"hn"}, It's important to note that the reques ...

Use Jackson to populate a Plain Old Java Object with an array from the main JSON node

Utilizing Jackson and RESTEasy for integration with an external API has been successful in populating simple objects into POJOs. However, a challenge arises when receiving an array of objects as a response. [ { "variable1": "someValue1", "variab ...

To efficiently update several rows in a single query, we require input in the form of a JSON object containing multiple sets of data

update users as u set -- postgres FTW email = u2.email, first_name = u2.first_name, last_name = u2.last_name from (values (1, '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c14131010150f3c0b1915111d121 ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits. The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled d ...

Invoke the URL with a query string and obtain the response from the specified web page

How can I make a button on my user.php page call action.php?name=john&id=10 without refreshing the page? The action.php page needs to process the query string data (name=john & id=10), execute some action, and then send a message back. Here is an ...

The newsfeed is not being shown in Tableview when using objective-c

The table view controller in BuyerSocialPage does not show the news feed. The BuyerSocialPage.h file is connected to the Newsfeed ViewController. @interface BuyerSocialPage : UIViewController <UITableViewDataSource,UITableViewDelegate> @end @imple ...

Error: The request to /api/auth/login in Postman failed unexpectedly

As I am working on developing an app using node.js and express, I encountered an error while making post requests in Postman. Cannot POST /api/auth/login%0A Below are the details of my app's structure along with the files involved: app.js const ex ...

Step-by-Step Guide on Retrieving Filtered Data using React Context API

Currently, I am in the process of developing a dashboard application using React.js, React Context API, and ApexCharts. The app will visualize a 1000-length JSON data on 7-8 different charts, along with 6-7 variable filters. Overview of the App Structure: ...

`What is the process for accessing page-specific data on Google Analytics using the analyticsreporting tool?`

I'm currently working on extracting specific analytics data using Google's analyticsreporting API v4. Below are the URLs of the pages I am analyzing: https://www.example.com/uiqueId1 https://www.example.com/uiqueId2 https://www.example.com/uiqu ...

The toggle feature in Bootstrap is stuck in the "on" position and refuses to "untoggle."

Currently, I am working on developing a basic website using Laravel and Vue.js. To ensure that the website is responsive, I integrated Bootstrap 4 into the project. For the most part, everything appears to be functioning correctly - the navbar collapses as ...

Sending JSON data through an HTTP POST request using Arduino

I am attempting to send JSON data using an Arduino. When running this code, I attempt to send the JSON data with a QueryString parameter. However, when I try this code, the server responds with a message stating that the QueryString format is incorrect, in ...

Retrieving an array of objects from JSON: "The most suitable method match contains some invalid arguments."

Currently, I am using JSON.net to parse the object data retrieved from a PHP script. My progress has been successful in parsing the array and breaking it down. However, when attempting to parse each object within that array, I encountered the following er ...

Jquery Plugin fails to generate dynamic elements effectively

I developed a masking jQuery script that dynamically adds elements to an existing input element. var link = $('<a title="show" role="link" href="#" class="masker-value">show</a>'); wrapper: function() { container = $(container) ...

Adjusting the view to focus solely on the visible portion of the webpage

Is there a way to achieve zooming in and out on a website similar to how it works on the site ? I want only the visible area to zoom in or out when users interact with their browser. I searched online for a solution but couldn't find one. Any suggesti ...

Res.write inexpressively proceeding without waiting for the completion of an array of promises

snippet const processAll = async (tasks) => { let processes = []; tasks.forEach(task => { if (task === "1") processes.push(asyncProcess1); if (task === "2") processes.push(asyncProcess2); if (task === "3&q ...

Utilizing a parent scope variable in a callback function

This question delves more into the concept of JavaScript Closures rather than Firebase. The issue arises in the code snippet below, where the Firebase callback fails to recognize the variable myArr from the outer scope. function show_fb() { var myAr ...