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

What is the conventional method for sending data by utilizing the output of a previous data submission in Node.js with Express and FaunaDB?

I am in the process of revising a project and have a question about how to post an array of data using the return value of a previous post request as the ID. Here is an overview of the data structure: Checklist A [ChecklistItem 1, ChecklistItem 2, Checkli ...

Placing the jQuery/javascript source pages right before the closing body tag

Multiple plugin instructions recommend placing the javascript/jQuery source right before the closing body tag. I wondered why this advice is given, but couldn't find a clear explanation for it. In my experience, placing the src file anywhere in the s ...

When the input CTRL+C is entered in the console, Node.js / JavaScript will output

I have a script that I use to restart another script. Here is the code snippet: catch(err){ console.log(err) webhook.send(`Error monitoring **www.-.com**, restarting monitor.`) await browser.close() await sleep(monitorDelay) return chec ...

What is the method for presenting text based on the chosen Select Option?

I attempted to achieve this using hrefs and ids, but it did not meet my requirements. This is the desired format: div.selectcountry { margin-bottom: 10px; font-family: arial; font-size: 12px; } div.countrydepartment { font-family: ...

Leveraging environmental variables in a Vue.js web application

The article I recently came across discussed how to effectively utilize environment variables in vuejs. Following the instructions, I set up my local .env.local file and also installed dotenv. VUE_APP_AUTH_AUTHORITY = 'http://localhost/auth' I ...

Can anyone please guide me on how to extract the IP address of a specific individual using Node.js?

There's an individual running some kind of exploit scanner on my server. I'm receiving strange requests like: IP ADDRESS: ::ffff:127.0.0.1 www-0 (out): POST /cgi-bin/php5?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64 ...

Using JQuery to eliminate Javascript code after setting up an event listener, but prior to the listener being activated

Having trouble finding a solution to my question through search. I'm sorry if it has already been asked before. I am attempting to define an event listener and immediately remove the JS code after defining it. The challenge is that I want the removal ...

Adjust the color of the font within a div element when hovering over it

I've been attempting to modify the text color and add an underline when a user hovers over it. Despite trying various methods, I haven't been successful. I scoured the internet for a solution but couldn't find one that met my specific requi ...

Transform Json data and add it to Yaml

When working with a Jenkins pipeline, my goal is to parse a JSON file and add a value to one of my YAML files. Here's the content of my JSON file: { "id": "test", "chef": { "attributes": { "example": { "example": "test" } ...

I made a request using the post type fetch to submit data to this form, but unfortunately, the server-side response returned

I encountered an issue where after sending the post type fetch to this form, I received 'undefined' on the server side. Here's the code snippet for my fetch request: const { text, id } = Data; fetch('http://localhost:3001/add' ...

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: Below is the code snippet: import React, { useState, Fragment } from "react"; import Sidebar from "../../User/Sid ...

How to manipulate iframe elements using jQuery or JavaScript

Hey there, I have a simple task at hand: I have a webpage running in an iFrame (located in the same folder on my local machine - no need to run it from a server) I am looking to use JavaScript to access elements within this iFrame from the main page. How ...

What could be causing the error when attempting to release this Node-MySQL pool?

My first attempt at utilizing connection pooling is with Node.js. I crafted a database connection module in Node.js to establish a single connection, which is then referenced within a pooling function for later use when passed to different modules. /* D ...

Create a Jest unit test for a specific function

I started my first unit test in react with jest this afternoon. The initial 5 tests I need to do involve testing the return functions, which isn't too difficult. However, I'm struggling to understand how to perform unit testing on my login funct ...

Improved methods for extracting nested JSON data from a Spark table

As a newcomer to Spark and Scala, I am facing the challenge of parsing a Nested JSON format column from a Spark Table. Let me show you an example row from the table: doc.show(1) doc_content object_id object_version {&quo ...

Ways to identify when a chemical reaction has taken place?

I have developed a Discord bot that interacts with an API related to a game server panel. The bot has tasks to start, restart, stop, and kill the server. I want to enable end users to trigger these tasks by reacting to a specific embed posted by the bot. ...

endless update cycle in Vue

I'm currently working on developing a custom component. And I have an idea of how I want to use it: let app = new Vue({ el:'#app', template:` <tab> <tab-item name='1'> <h1> This is tab item 1& ...

React Object Array Item State management

After spending a considerable amount of time on this task, I have been trying to achieve the functionality of changing a checked value upon checkbox click. Here is how my initial state is set up: const [todoList, setTodoList] = useState({ foundation: ...

Is there a way in jqGrid to invoke a function once the subGridRowCollapsed operation finishes?

I'm currently working with jqGrid's subgrids and I need a solution for invoking a specific method after collapsing a subgrid. Currently, my implementation is as follows: subGridRowCollapsed: function (subgrid_id, row_id) { adjust_slider_posi ...

Unable to detect the click event on Bootstrap accordion

I am currently utilizing Bootstrap to populate a table with data and then attempting to capture an accordion show event. My intention is to extract the div id in order to make an ajax call for more information on the respective item. Unfortunately, I have ...