Tips for simultaneously indexing multiple properties on a JavaScript object

Imagine having a JavaScript object structured like this:

var x = {
  'one': 1,
  'two': 2,
  'three': 3
}

Now, suppose you have an array containing the specific keys you want to access from this object.

Here are the keys you're interested in:

var keys = ['one', 'two'];

When you use these keys to extract information from the object, the desired output would be:

{
  'one': 1,
  'two': 2
}

In your hypothetical code snippet, you envision something like this:

var x = {
  'one': 1,
  'two': 2,
  'three': 3
}
var keys = ['one', 'two'];
var answer = x[keys];

However, as you already know, this approach doesn't work...

Is there an elegant way in javascript to achieve this? Can an array be used to index multiple properties of an object efficiently?

You might consider a for-loop solution that involves brute force, but is there perhaps a more sophisticated JavaScript feature that you're not aware of?

Any thoughts on this dilemma?

Answer №1

If you want to achieve optimal performance with a time complexity of O(n), you can employ the Array#reduce method.

const data = { 'one': 1, 'two': 2, 'three': 3};
const keys = ['one', 'two', 'five'];

const result = keys.reduce((acc, curr) => (curr in data && (acc[curr] = data[curr]), acc), {});
console.log(result);

Answer №2

By utilizing Object.fromEntries along with key mapping in your code, you can effectively create a new object based on specific keys.

var x = {
  'one': 1,
  'two': 2,
  'three': 3
};
var keys = ['one', 'two'];

const newObj = Object.fromEntries(
  keys.map(key => [key, x[key]])
);
console.log(newObj);

Answer №3

It seems like this code snippet could be helpful for your needs:

const obj = {
  'apple': 'red',
  'banana': 'yellow',
  'grape': 'purple'
}

const keys = ['apple', 'banana'];
let result = {};
keys.forEach(element => {result[element] = obj[element]})
console.log(result)

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 ThreeJS to calculate the rotation needed for one Vector3 to align with another Vector3

Recently delving into the world of ThreeJS, I've been exploring its potential for fun and creativity. My current project involves using ThreeJS in conjunction with aframe. The task at hand requires computing with ThreeJS to pass position and rotation ...

Leveraging JSON data to dynamically create HTML elements with multiple class names and unique IDs, all achieved without relying on

Recently, I've been working on creating a virtual Rubik's cube using only JS and CSS on CodePen. Despite my limited experience of coding for less than 3 months, with just under a month focusing on JS, I have managed to develop two versions so far ...

What are some ways to transfer data between parent and child components in Vue.js?

I have defined two different components: 'permissionTitle':customTitle, 'permissionItem':customItem, When displayed in the main template, they are structured as follows: <permissionTitle content="Brand Management"> ...

Modify the DOM at a later time once the images have loaded. This particular action is being executed within the context of an

main.ts myFunction(){ this.service.getData().subscribe( response => { this.handleData(response); }, error => console.log(error), () => console.log('request done') ...

The @azure/search-documents JavaScript SDK allows the SearchDocumentResult to retrieve facets

Is it normal for the facets property of SearchDocumentResult to only return undefined instead of the facets involved in the query and their values? If this is the expected behavior, is there an alternative method to access the facets using the sdk? ...

Troubleshoot the issue of ng-click not functioning properly when used in conjunction with ng-repeat with direct expressions

Having some trouble with an ng-repeat block and setting a $scope variable to true with an ng-click expression. It doesn't seem to be working as expected. Can anyone help out? Check the plnkr for more information. HTML: selected: {{selected}} < ...

Exploring the context of file upload events and analyzing javascript functionality

Can you help me conditionally trigger the file upload dialog using JavaScript based on an Ajax response? <input type="file" id="Upload"> I have hidden the input element as I don't want to display the default file upload button. Instead, ther ...

What to do when CSS Overflow doesn't work as expected?

Are there any alternatives for browsers that don't support CSS overflow? I am working on a new layout that heavily relies on the overflow property, however it seems like android browsers do not handle it well and as a result, my layout is broken. I am ...

Ways to ensure that text wraps to a new line when it exceeds the container's width

I am currently working on implementing a line of text within an ion-card element, but the challenge lies in the fact that the length of the text varies each time. In order to ensure that the entire text is visible and not cut off, especially on devices wit ...

Utilizing JQuery Definitions for File Upload in Typescript

I'm currently working with TypeScript and facing an issue with a file upload form. However, when I try to access the files from the input element in my TypeScript code, an error is generated. $('body').on('change', '#upload_b ...

A Guide to Testing Directives in Angular 2: Unit Testing Tips

Issue: My goal is to perform unit testing on an Angular 2 directive to ensure proper compilation. In the context of Angular 1, one could utilize the$compile(angular.element(myElement) service followed by calling $scope.$digest(). I am specifically looking ...

Discovering latitude and longitude coordinates from a map URL, then enhancing dynamism by utilizing the coordinates as parameters

Hello, I am currently learning Vue.js and have encountered a challenge with embedding Google Maps URLs. Despite my extensive research on Google, I have not been able to find the solution I need. Here is an example of the URL I am working with: "https: ...

Removing data from database with ajax

I am encountering an issue with deleting records from my database using ajax and jquery. When I click the button, nothing happens. Here is the relevant css code: <button class='delete_p' id_p='<?php echo $post_id; ?>'>x< ...

Defining the specific range for accessing array keys in PHP

Have you ever tried doing something like the following: some_function($text[0...5]); as opposed to: some_function($text[0], $text[1], $text[2], $text[3], $text[4], $text[5]); I am unfamiliar with any function that allows for this kind of syntax and des ...

How do I connect TypeORM to multiple databases?

I am faced with the challenge of creating tables in two different databases using TypeORM. Each table is associated with a specific database through the use of the @Entity decorator. However, I encounter an error stating that user x does not have write acc ...

Having trouble with shipit.js deployment: Error encountered - git checkout undefined

I have been using shipit.js to deploy my nodejs application on an Ubuntu 16.04 server successfully. However, I recently encountered the following error: ./node_modules/shipit-cli/bin/shipit production deploy start Running 'deploy:init' task... ...

Encountering a JS error while attempting to execute a basic HTTP request

I'm currently attempting to interact with a Gateway and decided to test out the https://www.npmjs.com/package/@types/request module. Below is the snippet of code I am trying to execute: export class OAuthAccessor { //some stuff public stat ...

Error VM5601:2 encountered - Unexpected token "<" found in JSON at position 10

I am trying to retrieve data using Ajax and jQuery, but I keep encountering an error that I cannot figure out how to fix. VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10 Below is the code I am working with. Model public f ...

What is the most efficient method for linking the hostname of my website to the file path within my Express.js static file server?

When using vanilla JavaScript in the browser, we can retrieve the hostname using: window.location.hostname However, if we are working with Node.js/Express.js on the server side, how can we achieve the same result? Furthermore, I am looking for a way to ...

Is there a way to extract all the titles from a json file that have a specific word in them?

Here is a function that returns props to an element named box in React. The MovieDatabase is a JSON file that contains titles of various movies. I am interested in displaying only the movies whose title includes "Star Wars". const showMovies = MovieData ...