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

Vuetify autocomplete with server-side functionality

I am looking to implement infinite pagination on the Vuetify autocomplete feature. My goal is to trigger the loading of a new page of items from the backend when I scroll to the end of the menu. Initially, I attempted using the v-intersect directive as fo ...

Tips for toggling an Electron.js submenu within a Vue.js Component based on a particular Vuex state

I've searched everywhere for a solution to this issue. Currently, I am working on a sample vue-vuex-electron app that I have developed. My goal is to dynamically enable or disable certain submenus within the app based on the vuex state 'isLogged ...

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Retrieving objects from Firebase in a loop using promises

Seeking guidance on handling promises in AngularJS as a newcomer. Struggling with merging data from two asynchronous arrays into a single array within a for-loop. Encountering a bug where the same picture is displayed for all entries despite different user ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

How to send cross-domain AJAX requests to RESTful web services using jQuery?

I have been utilizing Jquery Ajax calls to access RESTful webservices in the following manner. The web service is being hosted on a different domain. $.ajax({ type: "GET", url: "url for the different domain hosting", crossDomain: true, ...

The function $.fn.dataTable.render.moment does not exist in npm package

I have encountered an issue with my application that I am struggling to solve: I want to format dates in my data table using Moment.js like I have done in the following script: $().ready(function() { const FROM_PATTERN = 'YYYY-MM-DD HH:mm:ss.SSS&a ...

Smooth-scroll plugin does not activate active state (due to JS modification)

I'm currently facing an issue with a script that handles smooth scrolling and the active state on my main navigation. The plugin in question can be found at: It's important to note that the navigation bar is fixed and therefore has no height. T ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...

What is the best way to convert a repetitive string into a reusable function?

I am currently retrieving data from an API and I want to display it on my website in a more user-friendly manner. The challenge I'm facing is that the number of variables I need is constantly changing, along with their corresponding values. So, I&apos ...

The redirection to the HTML page happens too soon, causing the ASYNC functions to fail in saving the user's image and data to the server

Hey everyone! I'm facing an issue with async/await functions. Here's the code snippet from my backend where I'm trying to save details of a newly registered user. I'm puzzled as to why the Redirect() function is executing before the f ...

Using Next Js for Google authentication with Strapi CMS

Recently, I've been working on implementing Google authentication in my Next.js and Strapi application. However, every time I attempt to do so, I encounter the following error: Error: This action with HTTP GET is not supported by NextAuth.js. The i ...

CSS :contains selector after adding a script through Ajax append operation

Is there a way to change the text color in $('td:contains("text")').css('color','red') after an Ajax load script? Here is the main code snippet <div id="datatable"></div> <script src="https://code.jquery.com/j ...

console rendering duplication in React

Why am I seeing duplicate log entries in the console? While working on another project, I noticed that the number of HTML elements being added using jQuery was twice as much as expected (specifically while building a notification framework). To investigate ...

Is the ClientScriptmanager operational during a partial postback?

After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

The most efficient method for documenting $.trigger in JavaScript/jQuery is through the use of JSD

When it comes to documenting in jsDuck, what is the optimal method for capturing the following event trigger: $(document).trigger('myCustomEvent'); ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...

Transfer the layout from one HTML file to multiple others without the need to retype the code

I am working on developing an e-commerce website with HTML/CSS. My goal is to have a consistent template for all product pages that are accessed when clicking on a product. However, I do not want to manually code each page using HTML and CSS. Is there a mo ...