"Narrow down the object's properties based on an array of specified property

So here's the situation:

I have an object that looks like this
var obj = { name1: somevalue1, name2: somevalue2, name3: somevalue3}

Followed by an array

var arr = [name2, name3]

Both of these are dynamically generated. What I need to do is filter the object using the array (based on property names, not their values). However, all the methods I've come across so far focus on filtering by values. Therefore, the desired result should look like this:

var result = {name2: somevalue2, name3: somevalue3}

I'm working with Angular and Underscore. The filtering needs to be done in the controller, not in the template. Any assistance would be greatly appreciated!

Answer №1

If you want to selectively filter an object, you can make use of the _.pick method from Underscore.js.

var obj = { name1: "somevalue1", name2: "somevalue2", name3: "somevalue3"};
var keys = ["name1", "name2"];

console.log(_.pick(obj, keys));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Answer №2

To create a new object with key value pairs, you can iterate through the keys and populate the new object accordingly.

var sourceObj = { key1: 'value1', key2: 'value2', key3: 'value3' };
    keysToCopy = ['key2', 'key3'],
    copiedObj = Object.create(null);

keysToCopy.forEach(function (key) {
    copiedObj[key] = sourceObj[key];
});

console.log(copiedObj);

Answer №3

To retrieve an object using the reduce() method, follow this example:

var obj = {
  name1: 'somevalue1',
  name2: 'somevalue2',
  name3: 'somevalue3'
}
var arr = ['name2', 'name3']

var result = Object.keys(obj).reduce(function(r, e) {
  if (arr.indexOf(e) != -1) r[e] = obj[e];
  return r;
}, {})

console.log(result)

Answer №4

Loop through each item in the array and compare them to keys in an object, then add matching key-value pairs to a new result object.

const dataObj = { name1: somevalue1, name2: somevalue2, name3: somevalue3};// This is our object

const dataArray = [name2, name3];// Array of elements to retrieve values from obj

const filteredResult = {};// Object to store filtered values

dataArray.forEach((element) => { // Iterate through each element in the array
    if (dataObj[element]) // Check if the key exists in the object
        filteredResult[element] = dataObj[element]; // Add matching key-value pair to filtered object
});

console.log(filteredResult);

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 AJAX (jQuery) to process and refine JSON data through filtration

I need assistance with filtering a JSON array using AJAX but I'm unsure of how to proceed. { posts: [{ "image": "images/bbtv.jpg", "group": "a" }, { "image": "images/grow.jpg", "group": "b" }, { "image": "images/tabs.jpg", ...

Dynamically switch between doubling Ajax calls in JavaScript

Encountering an issue with a jQuery click function. Triggering the click event on an HTML button dynamically loads styled checkbox and toggle switches based on their stored on/off state in a database. An additional click function is added to each loaded t ...

Tips for managing a PHP post request without full knowledge of the variables to retrieve

My form allows users to dynamically add new lines using JavaScript. However, when they click the save button, I am struggling to capture and assign the new data to a variable. The current issue is that once the user adds new rows and clicks save, the rows ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

Oops! Looks like there was an issue with defining Angular in AngularJS

I am encountering issues while attempting to launch my Angular application. When using npm install, I encountered the following error: ReferenceError: angular is not defined at Object.<anonymous> (C:\Users\GrupoBECM18\Documents&bs ...

Guide on setting up haproxy as a reverse proxy for socket.io with SSL to avoid mixed content warnings

Over time, I've incorporated this configuration to integrate haproxy with node.js and socket.io. Highlighted sections from the haproxy setup: frontend wwws bind 0.0.0.0:443 ssl crt /etc/haproxy/ovee.pem timeout client 1h default_backend ...

Guide on incorporating botframework into a mobile application...?

Recently, I developed a chatbot utilizing the MS bot framework in Nodejs. To display the chatbot in an HTML format without iframes, I incorporated a React Component from the link provided at https://github.com/Microsoft/BotFramework-WebChat. At this point, ...

Displaying information from database using AngularJS

How can I display data from a database on my webpage? This is the JavaScript code: $scope.save = function() { var data = { subject: $scope.composeStory.subject, body: $scope.composeStory.body } $http.post( "insert.php", { ...

Mobile devices consistently experiencing issues with JavaScript generated elements overlapping

I'm currently in the process of creating a quiz based on a tutorial I found at https://www.sitepoint.com/simple-javascript-quiz/. While I followed the tutorial closely and integrated Bootstrap, I am encountering an issue specifically with mobile devic ...

Verifications in the realm of javascript

I created a custom form in Django which is functioning correctly. However, when I try to implement JavaScript validation, the validations do not seem to work as expected. I am looking to validate the form using JavaScript. Although it displays the alert me ...

how can one cycle through this demonstration

Within my code, there is a variable called "data" which holds an array of objects: [{"id_questao":1,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 1","id_formulario":1},{"id_questao":2,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 2","id_formulario":1} ...

Looking for help with aligning an icon to the right side of my text

I'm struggling with aligning the icon to the right of the quantity. When I use float:right, it places the icon at the far right of the cell instead of next to the text. Is there a way to get it to be on the right side of the text but directly adjacent ...

Transform the date format from yyyy-MM-dd'T'HH:mm:ss.SSS'Z' to dd-mmm-yyyy with the help of JavaScript

I am looking to convert date format from yyyy-MM-dd'T'HH:mm:ss.SSS'Z' to dd-mmm-yyyy when the dates are retrieved from a JSON object. Currently, I am utilizing the ng-csv plugin to download this JSON data, which is working properly. How ...

Effectively monitoring coordinates on both the client and server sides

I'm currently in the process of developing a multiplayer game using websockets, node, and JavaScript. I need advice on the most effective approach to update client information and manage their coordinates on the server. The method I am using at the mo ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

Why is there nothing showing up on the screen?

Just diving into Three.js and might've messed up somewhere. I'm trying to generate a geometry by using coordinates and surface data from a .k file. I checked the geometry.vertices and geometry.faces, they seem fine. I even played around with the ...

What is preventing my JavaScript from loading on my website when using window.onload?

I'm currently in the process of building an HTML page with Adobe Dreamweaver and utilizing the Live Preview feature to preview the page on a local server. However, I am facing some issues with my JavaScript code. I am attempting to populate a dropdown ...

Modify the text highlighted in bold within the AngularJS application

In my angular.js application, I have a table that displays elements. The name of these elements sometimes needs to be displayed in bold by adding <b> and </b> tags. However, instead of rendering the name as HTML code, it is showing up as a stri ...

Accessing the runtime 'this' value from an external function in JavaScript

this within a function is dynamically set at runtime: var person = { hello: function(thing) { console.log(this, " says hello " + thing); } } // the code: person.hello("world"); // is similar to: person.hello.call(person, "world"); Is there a ...

Search for a specific key within a list of dictionaries

I am working with an array of dictionaries: arrayDict: [ { Description: "Dict 0" Category: [ 'First', 'Both', ], }, { Description: ...