Tips for organizing a multi-layered object based on an internal value

I am currently facing a challenge in sorting a complex object. Here is the structure of the object:

[{
    "searchResultProperties": [{
        "key": "message_time",
        "value": 1542088800000
    }, {
        "key": "size_byte AVG",
        "value": 480
    }, {
        "key": "source_file",
        "value": "log"
    }, {
        "key": "source_host",
        "value": "lab8.domain.com"
    }],
    "show": false,
    "key": null,
    "type": null
}, {
    "searchResultProperties": [{
        "key": "message_time",
        "value": 1542096000000
    }, {
        "key": "size_byte AVG",
        "value": 373
    }, {
        "key": "source_file",
        "value": "log"
    }, {
        "key": "source_host",
        "value": "lab8.domain.com"
    }],
    "show": false,
    "key": null,
    "type": null
}, {
    "searchResultProperties": [{
        "key": "message_time",
        "value": 1542103200000
    }, {
        "key": "size_byte AVG",
        "value": 683
    }, {
        "key": "source_file",
        "value": "log"
    }, {
        "key": "source_host",
        "value": "lab8.domain.com"
    }],
    "show": false,
    "key": null,
    "type": null
}]

Essentially, this is an array of objects containing a property named "searchResultProperties", which consists of an array of objects with properties "key" and "value".

My objective is to sort the objects based on the "key" property, specifically "size_byte AVG".

Answer №1

The function find can be utilized to search for objects with the key size_byte AVG, while the function sort is ideal for sorting the array.

This particular method sorts the data in ascending order

let arr = [{    "searchResultProperties": [{        "key": "message_time",        "value": 1542088800000    }, {        "key": "size_byte AVG",        "value": 480    }, {        "key": "source_file",        "value": "log"    }, {        "key": "source_host",        "value": "lab8.domain.com"    }],    "show": false,    "key": null,    "type": null}, {    "searchResultProperties": [{        "key": "message_time",        "value": 1542096000000    }, {        "key": "size_byte AVG",        "value": 373    }, {        "key": "source_file",        "value": "log"    }, {        "key": "source_host",        "value": "lab8.domain.com"    }],    "show": false,    "key": null,    "type": null}, {    "searchResultProperties": [{        "key": "message_time",        "value": 1542103200000    }, {        "key": "size_byte AVG",        "value": 683    }, {        "key": "source_file",        "value": "log"    }, {        "key": "source_host",        "value": "lab8.domain.com"    }],    "show": false,    "key": null,    "type": null}],
    target = "size_byte AVG",
    compare = (a, b) => a.find(({key}) => key === target).value - b.find(({key}) => key === target).value,
    sorted = arr.sort(({searchResultProperties: a}, {searchResultProperties: b}) => compare(a, b));

console.log(sorted);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To easily sort an array based on a specific property, you can utilize the Array.prototype.sort() function. This function allows you to compare two objects and specify whether one should come before the other based on your custom logic. For more details, you can refer to the documentation at [ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort ]

array = [{
    "searchResultProperties": [{
        "key": "message_time",
        "value": 1542088800000
    }, {
        "key": "size_byte AVG",
        "value": 480
    }, {
        "key": "source_file",
        "value": "log"
    }, {
        "key": "source_host",
        "value": "lab8.domain.com"
    }],
    "show": false,
    "key": null,
    "type": null
}, {
    "searchResultProperties": [{
        "key": "message_time",
        "value": 1542096000000
    }, {
        "key": "size_byte AVG",
        "value": 373
    }, {
        "key": "source_file",
        "value": "log"
    }, {
        "key": "source_host",
        "value": "lab8.domain.com"
    }],
    "show": false,
    "key": null,
    "type": null
}, {
    "searchResultProperties": [{
        "key": "message_time",
        "value": 1542103200000
    }, {
        "key": "size_byte AVG",
        "value": 683
    }, {
        "key": "source_file",
        "value": "log"
    }, {
        "key": "source_host",
        "value": "lab8.domain.com"
    }],
    "show": false,
    "key": null,
    "type": null
}]

array = array.sort((a,b) => a.searchResultProperties.find(obj => obj.key === "size_byte AVG").value - b.searchResultProperties.find(obj => obj.key === "size_byte AVG").value )

console.log(array);

Answer №3

You have the option to utilize the sort method alongside the find method.

The sort method requires two values as arguments. By using the find method, we are able to locate the array element with the key 'size_byte AVG' and extract the value for comparison.

let arr = [{"searchResultProperties": [{"key": "message_time","value": 1542088800000}, {"key": "size_byte AVG","value": 480}, {"key": "source_file", "value": "log"}, {"key": "source_host","value": "lab8.domain.com"}],"show": false,"key": null, "type": null}, { "searchResultProperties": [{"key": "message_time","value": 1542096000000}, {"key": "size_byte AVG","value": 373}, {"key": "source_file","value": "log"}, {"key": "source_host","value": "lab8.domain.com"}],"show": false,"key": null, "type": null}, {"searchResultProperties": [{"key": "message_time","value": 1542103200000}, {"key": "size_byte AVG","value": 683 }, { "key": "source_file","value": "log"}, {"key": "source_host", "value": "lab8.domain.com"}],"show": false,"key": null,"type": null}]

let op = arr.sort((a,b)=>
         a.searchResultProperties.find(e=>e.key==='size_byte AVG').value -
         b.searchResultProperties.find(e=>e.key==='size_byte AVG').value)

console.log(op)

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

Step-by-step guide on making a post request to the Facebook Graph Api with Httparty in a Rails application

I'm currently working on developing a bot for Facebook Messenger, and I need to make a post request call to the Facebook Graph API. The sample code provided by Facebook is in Node.js, but I am working with Rails as my backend framework. Sample Code ...

Enter the Kannada language into the HTML text box or input field

My html form consists of about 15 - 20 input and textarea fields. As a user, how can I enter information in Kannda or any other local language? https://i.stack.imgur.com/60PVT.png ...

What is the best way to showcase MongoDB data in ReactJS upon clicking a button?

I have embarked on a React project using Express.js, MongoDB, React.js, and Node.js. My goal is to fetch data from a backend API that is running on port 5000. When I test the API using Postman, everything works perfectly fine. The data is displayed in the ...

Incorporating SQLSRV results into clickable <td> elements: A dynamic approach

As a newcomer to the world of JS/PHP/web development, I'm seeking help with a seemingly simple task. My goal is to make each <td> element in a table clickable, and retrieve the text contained within the clicked <td>. Currently, I have a S ...

Tips for Effectively Declaring a Variable with React's useState

How should I correctly specify variable types in useState? In the code below, the value for alert must be either "success","warning", "error", or "info" const [alertValue, setAlertValue] = useState("error" ...

What is the best way to arrange elements based on the numeric value of a data attribute?

Is there a way to arrange elements with the attribute data-percentage in ascending order, with the lowest value first, using JavaScript or jQuery? HTML: <div class="testWrapper"> <div class="test" data-percentage="30&qu ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

Setting the second tab as the primary active tab

I am currently working on a script that is well-known, and everything is functioning perfectly. However, I want to change it so that when the page is first opened, it displays the second tab instead of the first one (the first tab being a mail compose tab ...

AngularJS is not triggering the $watch function

I'm facing an issue with the $scope.$watch function, as it's not being triggered when expected. In my HTML document, I have a paginator using bootstrap UI: <pagination total-items="paginatorTotalItems" items-per-page="paginatorItemsPerPage" ...

Referencing a JSON object

Here is a JSON list of search terms: [ "halo", [ "halo reach", "halo anniversary", "halo 4", "halo 3", "halo mega bloks", "halo 2", "halo sleepsack", "halo wars", "halo reach xbox 360", "halo combat evolved" ], ...

What's the best way to update the value of a TextInput field?

Previously, I was updating the text input using local state. Here's an example: state = {name: ''} ... <AddEditFormInputs onChangeText={name => this.setState({ name })} textStateValue ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

What is the method to determine the length of a string with TypeScript?

Looking to derive the numerical length of a string: type Length = LengthOfString<"hello"> // ^? should equal 5 Feeling a bit lost on how to approach this. Any guidance on how to achieve this? (Currently diving into typescript's typ ...

Transferring identification data between views within an application (AngularJS, NodeJs, HTML)

I'm working on an HTML page that lists users from MongoDB. The page allows for deleting and updating users. I am encountering an issue with the update button - I want a new HTML page to appear with a form when the button is clicked, capturing the user ...

Accessing Jquery's $.get function is currently not possible

I am experiencing difficulty fetching the contents of a json.txt file located in the same directory as this markup. Additionally, there are no errors appearing in Firebug. <!DOCTYPE html> <html> <head> <script type="text/ja ...

It appears that the setup function completes its execution before the onMount function is called in Vue 3

createApp({ setup() { let price = 0 onMounted() { // axios price = axios.response } return { price } } }).mount('#app') HTML <h6 id="app" class="mb-0"> ...

Clicking a button in Angular JS to refresh a specific ID element

Just diving into AngularJS for my mobile web app development. I have different id divs for each view, as that's how AngularJS operates with one HTML page. My goal is to use specific javascript for each id page, as they need to retrieve JSON data objec ...

Is it possible to access the names of objects within an array in JavaScript?

If objects are created and placed in an array, does the array store only the properties of the objects or also their names? This may seem like a simple question, but I've been unable to find a clear answer. var boxA = {color: "red", width: 100}; var ...

Common Errors in Angular 2 due to TSLint

I am encountering multiple errors in my code. I am using Angular 2 with TSLint: constructor(http: Http) { this.http = http; --> let currentUser = JSON.parse(localStorage.getItem("currentUser")); this.token = currentUser && currentUser.t ...

Implementing additional states in an AngularJS app configuration with Ui-Router

Currently tackling a major application with numerous routes for its different components, my team and I have decided to break down the routes into separate files instead of cramming everything into one large file. In attempting to create a variable and im ...