What is the best approach for choosing an object's properties by delving into its nested properties with Lodash?

My dilemma involves selecting the properties of an object based on certain values within the nested properties. I have been attempting to achieve this using Lodash's pick() method, with the code looking something like this:

const object = {
    a: {x: true, y: true,},
    b: {x: true, y: false,},
    c: {x: true, y: true,},
  };
  
  _.pick(object, y,);
  

The expected outcome should be as follows:

{
    a: {x: true, y: true,},
    c: {x: true, y: true,},
  }
  

However, instead of the desired result, an error is encountered.

Execution halted due to Syntax Error on Line 6
Unexpected token, expected , (6:2)

I am puzzled by what mistake I may be making in this process.

Note: If there isn't a tidy solution available with Lodash, I am open to exploring an elegant plain Javascript alternative.

Answer №1

To achieve this, you can utilize the _.pickBy() method and specify the y property as the predicate:

const object = {
  a: {x: true, y: true,},
  b: {x: true, y: false,},
  c: {x: true, y: true,},
};

const result = _.pickBy(object, 'y');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

If lodash is not available, an alternative approach involves using Object.entries() to convert the object into an array of [key, value] pairs. Then filter based on the y property of the value, and finally transform it back to an object with Object.fromEntries():

const object = {
  a: {x: true, y: true,},
  b: {x: true, y: false,},
  c: {x: true, y: true,},
};

const result = Object.fromEntries(
  Object.entries(object)
    .filter(([, o]) => o.y)
);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Answer №2

The reason for your syntax error lies in the absence of a comma in the definition of object. Perhaps reconsider using pick, and instead try something like this:

const object = {
  a: {x: true, y: true,},
  b: {x: true, y: false,},
  c: {x: true, y: true,},
};

_.filter(object, (e) => e.y);

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

Is there a way to modify the text within a "span" element that directly follows an "i" element using jQuery?

I am attempting to modify the text displayed on a button within a plugin by using jQuery. Here is the outer HTML: <button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour"> <span class="ladda-label"> <i class="ab-hour ...

Extract the response from codebird and store it in an array (or access the JSON data from the codebird's reply)

I am currently working on retrieving data from Twitter using codebird in my JavaScript script. The issue I am facing is that codebird's response is in the form of an object rather than JSON. As a result, I am unable to use eval() to convert the JSON t ...

What is the most efficient way to calculate the current percentage of time that has elapsed today

Is there a way to calculate the current time elapsed percentage of today's time using either JavaScript or PHP? Any tips on how to achieve this? ...

Checking and merging arrays in Javascript

I have a unique challenge involving two arrays of objects that I need to merge while excluding any duplicates. Specifically, if an object with the key apple: 222 already exists in the first array, it should be excluded from the second array. Please see be ...

Obtain the VW/VH coordinates from an onclick action in JavaScript

With this code snippet, you'll be able to retrieve the x and y coordinates of a click in pixels: document.getElementById("game").addEventListener("click", function(event) { console.log(event.clientX, event.clientY); }); However ...

How to Stop the Window from Closing with jQuery

Is there a way to prompt the user for confirmation before they leave the page if they click the close button, similar to how it's done in Google Docs? How can this be achieved using jQuery? ...

jQuery plugin that controls scrolling speed using the mousewheel

I am trying to replicate the header design of Google+ which includes a search bar that moves when scrolling. Specifically, when the user scrolls down, the search bar shifts to top:-60px and the second horizontal menu shifts from top:60px to top:0 becoming ...

What is the best way to merge two objects in a JSON array and separate them with a comma?

Hey there, I could use some assistance with formatting a code snippet. I have written JavaScript code to parse JSON data which includes latitude and longitude information: const api_url = 'json.php' async function getjsonlatest() { const resp ...

Could you provide the parameters for the next() function in Express?

Working with Express.js to build an API has been a game-changer for me. I've learned how to utilize middlewares, handle requests and responses, navigate through different middleware functions... But there's one thing that keeps boggling my mind, ...

Getting the Object Id from HTML and passing it back to the Controller in MVC using C#

JQuery: $("#shoppingCart").droppable( { accept: ".block", drop: function (ev, ui) { var droppedItem = $(ui.draggable).clone(); $(this).append(droppedItem); $.ajax({ type: "POST", ...

Exploring how Node.js, Express.js, and Mongoose work together to handle

I am experiencing difficulties with handling data received from APIs, as it returns null and doesn't wait even though I have used async/await functions. My goal is to retrieve data from the first URL, then gather data from other URLs based on the res ...

Steps for sending an array from PHP to an AJAX response in JavaScript

How can I send an array from PHP to an AJAX call? AJAX call: $.post('get.php', function(data) { alert(data); }); get.php $arr_variable = array('033', '23454'); echo json_encode($arr_variable); When the data is alert ...

Can you locate the hiding spot of the express-session cookie?

After setting a very short cookie max-age (10 secs) in my express-session, I confirmed that it is working as expected: app.use(session({ secret: 'xxx', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 10000 } })); ...

Developing AJAX Post Functionality Using Only Vanilla Javascript

Can I achieve AJAX Post in Pure Javascript without using the xmlhttprequest object? Consider a basic form like this: <form action="request.php" id="register_form"> <input type="text" name="first_name" placeholder="First Name"> <input t ...

Conceal the Vue router on a webpage

How can I hide the vue-router from my login page? I want to remove the menu on the Login page. Is it possible and how would I achieve that? Here is the code for the Login page: Login <template> <div> <h1>Login</h1> ...

Accessing the properties of a module in Javascript - a foolproof guide to making the most

In the constants.js file, I have defined the following code: var constants = ( conversationUsername: "user1", conversationPassword: "pass1", conversationVersionDate: "date1", conversationWorkspaceId: "work1" }; module.exports.constants ...

Tips for Making Changes to a Polyline on Google Maps

I am currently utilizing the Directions Service provided by Google Maps V3 API, and I have a specific requirement to shorten the length of one of the steps by 1 meter (let's assume it's the final step). Issue: The directionResult can be viewed h ...

The Document.querySelector() method is not displaying every element

As a beginner, I am currently exploring the world of relative CSS selectors and JSPath for my automation scripts. During my journey, I noticed that there are differences in the return statements between these two methods. Below is an example demonstrating ...

Unable to interact with a div button using Selenium WebDriver

var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); driver.get('https://www.tumblr.com/login'); driver.findElement(webdriver.By.id(&ap ...

How to maintain global position, rotation, and scale when adding an object to a group in Three.js

I need to transfer an object from one group (or world/scene) to another group while maintaining its global transformation. I want the object to appear unchanged. Here is an example of what I am trying to achieve: //store the current world transformation ...