Dotted JavaScript property within an object

Having trouble sorting an array of objects using the lodash orderBy function because it doesn't work when the iteratees contain a dot in the middle.

For a better understanding of the issue, check out this plunker. plunker

ar users = [
     { 'user': 'fred',   'age': 48 },
     { 'user': 'barney', 'age': 34 },
     { 'user': 'fred',   'age': 40 },
     { 'user': 'barney', 'age': 36 }
];

_.orderBy(users, ['user', 'age'], ['asc', 'desc']);

Any assistance on this issue would be greatly appreciated.

Thank you for your help.

Answer №1

If you're looking to access exotic key names, one solution is to create a function specifically for that purpose.

const
    getPDot = o => o.value['p.'].val,
    data = [{ id: 'b', value: { 'p.': { val: 2 } } }, { id: 'a', value: { 'p.': { val: 1 } } }, { id: 'c', value: { 'p.': { val: 3 } } }];


console.log(_.orderBy(data, [getPDot], ['asc']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js></script>

An alternative is to take a dynamic approach using a closure over the key.

const
    getValue = key => o => o.value[key].val,
    data = [{ id: 'b', value: { 'p.': { val: 2 } } }, { id: 'a', value: { 'p.': { val: 1 } } }, { id: 'c', value: { 'p.': { val: 3 } } }];


console.log(_.orderBy(data, [getValue('p.')], ['asc']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js></script>

For those using ES5, a similar approach can be achieved with a function and closure over the key variable.

const
    getValue = function (key) {
        return function (o) {
            return o.value[key].val;
        };
    },
    data = [{ id: 'b', value: { 'p.': { val: 2 } } }, { id: 'a', value: { 'p.': { val: 1 } } }, { id: 'c', value: { 'p.': { val: 3 } } }];


console.log(_.orderBy(data, [getValue('p.')], ['asc']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js></script>

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

Assistance from Meteor for storing Cached Cursors

I have a Template that features a select element allowing users to filter through a collection of Objects displayed on a table. The result of the select is stored in a ReactiveVar, which is then utilized in querying a Helper to retrieve the Objects for the ...

Using VueJS to showcase user input in a dynamic list and a pop-up modal

I am attempting to achieve the following: Use a v-for loop to display form input (name, position, company) as an unordered list, showing only the name input and a button for each person When a button is clicked, a modal will appear displaying all the data ...

What is the best way to connect a Jquery plugin to a table within a partial view following an ajax request?

I have a main view that utilizes a partial view to display items in a table format. Main View (Enclosed within a div, it references the Partial View) <div id="divList"> @Html.Action("_list") </div> Partial View (Displaying a list of it ...

Problem with Angular-UI Bootstrap Tooltip

It seems like due to the current structure of the page, the tooltip functionality is not functioning properly. index.html <div class="main-navigation"> <div rt-tool-menus-"menus" selected="selectedMenus" tooltip="{{appController.displayName}} ...

What are alternative methods to exchange data between two controllers besides using services and rootscope?

In a recent interview, I was asked about sharing data between two controllers in Angular. I'm familiar with using services and root scope for this purpose. However, I'm curious if there's an alternative method to pass data between controller ...

Issues with Implementing Scroll Directive in Angular JS

Apologies for asking what may seem like a silly question. I'm still new to using AngularJS and recently came across a neat little scroll directive on http://jsfiddle.net/88TzF/622/. However, when I tried implementing the code in the HTML snippet below ...

Utilizing Angular to fetch data via CORS from a Django Rest Framework backend with authorization restrictions

I am currently working on an Angular application that is consuming a CORS-enabled REST API (Django Rest Framework). I am trying to retrieve all users from http://127.0.0.1/api/users. When accessing the data, I have encountered an issue when the Django view ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

Implementing automatic redirection upon clicking using React without the need for manual clicking

I'm experiencing an issue where the page seems to automatically navigate to another page without clicking on the div. Can anyone explain why this is happening? Here's the code snippet for reference: import React, { Component } from "react&q ...

The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats const arr1 = [ { "elementName": "one" }, { "elementName": "two" } ] const arr2 = [ { "type": "RPT_PROPERTY_DEMOGRP", "values": [ { "label": "HH" }, { " ...

In order to preserve the data inputted by the user within a file

Check out this HTML code snippet:- ` AngularJS | $http server <div ng-controller="people"> <ul> <h2> Names and Ages of programmers: </h2> <li ng-repeat="person in persons"> { ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...

Image gradually disappears after being loaded via ajax request

I am trying to achieve a fade-in effect for images after they have been loaded following an ajax call. The goal is to make the fade-in occur smoothly, rather than having the user observe the image loading process. Is there anyone who can assist me with ...

What is the best way to simulate an unexported function in Javascript jest environments?

Testing a module in my vuejs project is what I'm currently focusing on. import { getBaseUrl } from "@/application/api/baseUrl"; export default ( uri: string, requestBody: Record<string, string | number> ): void => { let form ...

What is the most effective method for storing an object in React?

I am facing an issue with storing my Object of my Checkout-Cart in a React Variable. I attempted to use the useState Component, but unfortunately, it did not work. Here is the object that I receive from my NodeJs Backend : [ { product_uuid: '3b ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

sending information to $modal in AngularUI

Hey there, I've been working with Angular ui $modal to create some modals lately. However, I've been running into issues when trying to pass data to the modal using resolve. Does anyone have any tips on how to solve this problem? // Manage Vi ...

Ways to conceal ad container when ad space remains empty

After setting up my ad HTML like this: <div class="ad-container"> <p>Ad slot #1</p> <div id="ad-slot-1" class="ad-slot"></div> </div> I implemented the code below to collapse the ad if ...

Tips on adjusting a position that shifts with changes in window size

Working on a website for my grandpa, I'm planning to include a small biker character that runs across the screen. When hovered over, he stops and advises "wear a helmet." The animation works well, but there's an issue with the positioning when th ...