Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this:

obj: {
  1: {...},
  2: {...},
  3: {...},
  4: {...},
  5: {...},
}

On the other hand, there is a simple array as well:

arr: [1,3,5,7]

The goal here is to filter the object based on keys present in the array. For example:

obj: {
  1: {...},
  3: {...},
  5: {...},
}

Currently, the code being used is:

var select = (arr, obj) => arr.reduce((r, e) => 
  Object.assign(r, obj[e] ? { [e]: obj[e] } : null)
, {});

var output = select(arr, obj);

There seems to be sporadic issues with the functionality. It's important to note that JQuery cannot be utilized in this scenario. Any suggestions or assistance would be greatly appreciated.

Answer №1

Utilize Object.fromEntries(), Object.entries(), Array.prototype.filter(), and Array.prototype.includes() for the task of selecting specific keys within the arr:

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = Object.fromEntries(
  // Pay attention that `key` is a `string`, so we use `+`:
  Object.entries(obj).filter(([key]) => arr.includes(+key))
);

console.log(filtered);

You can also achieve this with a simple for loop, specifically using for...of. In this case, utilize again Array.prototype.includes() to select desired keys instead of eliminating unwanted ones. Also include

Object.prototype.hasOwnProperty()
to prevent the addition of keys not present in obj:

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = {};

for (const key of arr) { 
  // Ensure you check for `hasOwnProperty` to avoid adding the key `7` with value `undefined`:
  if (obj.hasOwnProperty(key)) filtered[key] = obj[key];
}

console.log(filtered);

Alternatively, you could apply the same logic by utilizing Array.prototype.reduce():

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = arr.reduce((newObj, key) => {
  // Add values to `newObj` rather than `filtered` this time:
  if (obj.hasOwnProperty(key)) newObj[key] = obj[key];
  
  // Always remember to return `newObj`:
  return newObj;
}, { })

console.log(filtered);

Lastly, if you are incorporating Lodash, consider using _.pick:

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = _.pick(obj, arr);

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

Answer №2

If you're working in a modern setting (or using the right polyfills), the recommended methods are Object.entries, Array.prototype.filter, and Object.fromEntries. You can use them like this:

const result = Object.fromEntries(
    Object.entries(obj)
        .filter(([key, value]) => arr.includes(+key))
);

Check out this live example:

const obj = {
  1: {name: "one"},
  2: {name: "two"},
  3: {name: "three"},
  4: {name: "four"},
  5: {name: "five"},
};

const arr = [1,3,5,7];

const result = Object.fromEntries(
    Object.entries(obj)
        .filter(([key, value]) => arr.includes(+key))
);

console.log(result);

Alternatively, you can opt for a simpler loop approach:

const result = {};
for (const [key, value] of Object.entries(obj)) {
    if (arr.includes(+key)) {
        result[key] = value;
    }
}

Here's the live demonstration:

const obj = {
  1: {name: "one"},
  2: {name: "two"},
  3: {name: "three"},
  4: {name: "four"},
  5: {name: "five"},
};

const arr = [1,3,5,7];

const result = {};
for (const [key, value] of Object.entries(obj)) {
    if (arr.includes(+key)) {
        result[key] = value;
    }
}

console.log(result);


In both approaches above, it's important to note the + before key in the filter function. As the array consists of numbers, while object keys are always strings or Symbols (in this case, strings), conversion is necessary for includes to work properly.

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 best way to obtain a direct file link from a server URL using JavaScript?

After acquiring a file located at /home/johndoe/index.html, I am utilizing a tool like XAMPP to host, with the folder /home being hosted on localhost. The variables in play are as follows: $server_addr = "localhost"; $server_root = "/home"; $file_dir = " ...

What is the best way to divide an array into pairs and store them in separate arrays?

I'm attempting to challenge my JavaScript skills and faced with a dilemma. There is an array containing data var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];. The goal is to pair the elements and generate a new array of arrays such as var newArray = [[1 ...

Extracting specific key-value pairs from JSON data

Working with JSON data, I encountered a need to pass only specific key-value pairs as data to a component. Initially, I resorted to using the delete method to remove unwanted key-value pairs, which did the job but left me feeling unsatisfied. What I truly ...

Adjust the opacity of a div's background without impacting the children elements

I am currently working on a dynamic content display in my HTML page using some knockout code. The setup looks like this: <section id="picturesSection" class="background-image" data-bind="foreach: { data: people, as: 'person'}"> <div ...

Tips on verifying the count with sequelize and generating a Boolean outcome if the count is greater than zero

I'm currently working with Nodejs and I have a query that retrieves a count. I need to check if the count > 0 in order to return true, otherwise false. However, I am facing difficulties handling this in Nodejs. Below is the code snippet I am strugg ...

I'm having trouble getting Tailwind CSS colors to work with my Next.js components. Any tips on how to apply background colors

https://i.stack.imgur.com/8RGS3.png https://i.stack.imgur.com/FRTOn.png Hey there! I'm currently experimenting with using Tailwind background colors in my Next.js project. However, I'm facing an issue where the background color is not being appl ...

`What are some strategies for addressing an intermittent issue in an application utilizing Vue Apollo?`

Intermittently, I encounter the following error: vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'books' of undefined" discovered in ---> at src/views/Home.vue at src/App.vue warn @ vue.runtim ...

Using JQuery toggleclass to add transitioning effects to a :after element

I'm using the toggleClass function to add the class .expend to a div with an ID of #menu, which increases the height of the menu from 100px to 200px with a smooth transition effect. I also have a pseudo-element #menu:after for aesthetic purposes. My ...

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...

Ways to center text horizontally in a line with the help of bootstrap styles?

.list-group-item{ width: 165px; height: 32px; line-height: 1px; text-align: center; margin-bottom: 1px; margin-top: 58px; margin-left: 20px; } <ul class="list-group" v-if="showSearchHistory"> <li class="list-g ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...

Is there a way to streamline and optimize this React/Material UI code for faster performance?

There seems to be a lot of repetition in the code that needs to be cleaned up. I'm wondering if the switch statement is necessary. It looks like it requires the muiTheme palette to be passed this way. Also, can these theme constants be placed in a sep ...

Discover the simple steps to include row numbers or serial numbers in an angular2 datagrid

Currently, I am utilizing angular2 -datatable. Unfortunately, I am facing an issue where the correct row numbers are not being displayed in their corresponding rows. Whenever a user moves to the next page using the paginator, the datatable starts countin ...

Executing functions in a loop using Angular

Within my component, there is a foreach loop triggered when a client is selected. Inside this loop, I need to execute a function within the same component. The issue arises with calling the function using `this.functionName()` because 'this' no ...

Engage with React JS arrays of objects

I have a specific object structure that looks like the following: [ { "periodname": "Test", "periodtime": "" }, { "periodname": "", "periodtime&quo ...

I'm attempting to store the information from fs into a variable, but I'm consistently receiving undefined as the output

I'm currently attempting to save the data that is read by fs into a variable. However, the output I am receiving is undefined. const fs = require("fs"); var storage; fs.readFile("analogData.txt", "utf8", (err, data) =&g ...

What steps should I take to make sure the vuex store is included in my build process?

I am currently working on a Vue application using vue cli 3. I found a guide here that explains how to build the app with vue-cli-service build --target wc --name my-element [entry] In order to test the output, I have created an index.html file: <!D ...

Modifying the Vue.js Vue3-slider component for custom color schemes

Currently, I am using the vue-slider component and would like to customize the color of the slider itself. The specific class that needs to be styled is "vue-slider-dot-tooltip-inner". Below is a screenshot displaying the original CSS styling for vue-slid ...

How come the sound is played after the command is given?

function myTimer() { randint= Math.floor(Math.random() * 10)+1; randstimuli=gorilla.stimuliURL(dict[randint]); var audio = new Audio(randstimuli); audio.play(); var start=Date.now(); var ans=prompt("was the last number the same as t ...

Leveraging two AJAX requests within a single function

I am working on creating an ajax function to post data that I've retrieved using another ajax function. While I have figured out how to use a callback function, I am struggling with passing the data from one function to the other. Here is what I have ...