Compare object key and array in Javascript to create a new object

Can you aid me in achieving the following output by comparing var1 and var2, and obtaining the output based on var2 where the keys are provided in a string array?

var1 = {a:1, b:2, c:3, d:4};
var2 = ['a', 'd'];

The expected output is:

var3 = {a:1, d:4};

Answer №1

let filteredVars = var2.reduce((accumulator, current) => {
  if (var1[current]) {
    accumulator[current] = var1[current];
  }
  return accumulator;
}, {})

Check out this code snippet on JSFiddle.

Answer №2

Utilizing the .forEach method

let object1 = {x:1,y:2,z:3,w:4}; let keys =['x','w'];
let result = {};

keys.forEach(key=>{
 result[key] = object1[key]
})


console.log(result)

Answer №3

One way to accomplish this task is by utilizing the Object.entries method to iterate through the key-value pairs of an object.

var obj1 = {a:1, b:2, c:3, d:4}; 
var keysToCheck = ['a', 'd'];
var filteredObj = {};

for(let [key, value] of Object.entries(obj1)) {
  keysToCheck.forEach(targetKey => {
    if(key === targetKey) {
      filteredObj[key] = value;
    }
  });
}

console.log(filteredObj);

Answer №4

To transform each key in the variable var2 into an object with the key and its corresponding value, you can utilize the .map() method. This mapped array can then be used to assign each object to a new object using Object.assign():

const var1 = {a:1,b:2,c:3,d:4};
const var2 = ['a','d', 'f'];

const var3 = Object.assign({}, ...var2.map(id => id in var1 ? {[id]: var1[id]} : {}));
console.log(var3);

Alternatively, you can consider using Object.fromEntries() if your environment supports it:

const var1 = {a:1,b:2,c:3,d:4};
const var2 = ['a','d', 'f'];

const var3 = Object.fromEntries(var2.filter(id => id in var1).map(id => [id, var1[id]]));
console.log(var3);

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

Attempting to showcase information on the Angular frontend

When attempting to retrieve the Street name, I am seeing [object Object]. What is the optimal approach for displaying JSON data on the client side? I managed to display a street name but struggled with other components. How can I access the other elements ...

The reference to the Material UI component is not functioning

I am currently working on a chat application and have implemented Material UI TextField for user message input. However, I am facing an issue with referencing it. After researching, I found out that Material UI does not support refs. Despite this limitatio ...

Can someone assist me in determining the UV mapping process from Ricoh Theta S Dual Fish Eye to a Three.js r71 SphereGeometry?

Currently, I am attempting to replicate the three.js panorama dualfisheye example using Three.js version r71. It is crucial for me to adhere to r71 because I plan to integrate this code into the Autodesk Forge viewer, which relies on Three.js r71. I have ...

Next.js Content Switching: A Step-by-Step Guide

On my app, I have a main dashboard featuring a sidebar navigation and content container. However, being new to next.js and its routing system, I'm unsure how to update the content when a user navigates using the sidebar. Do I need to create separate p ...

Is it possible to automatically adjust the text color to match the background color?

In my hypothetical scenario, I am part of a group chat where the owner has the ability to change the background color of the chat bubbles. Each user's username appears on top of their respective bubble in one of ten pre-assigned colors. However, not a ...

Searching for and replacing anchor tag links within a td element can be achieved using PHP

I am currently customizing my WordPress website and I need to update the URL (product link) of the "product-image" on the "cart" page. I have the following dynamic code: <td class="product-name" data-title="Product"> <a href=&q ...

Error encountered with Jquery script: "Unauthorized access"

I'm currently working on a script that involves opening a child window, disabling the parent window, and then re-enabling the parent once the child window is closed. Here's the code snippet: function OpenChild() { lockOpportunity(); if (Clinical ...

"Exploring the world of JSON in the realm of

I am attempting to showcase JSON data using jQuery Mobile Is there something incorrect on this page? Check out my code here! Thank you! ...

What is the best way to pass the value of a selected option to an express server

<label for="exampleFormControlSelect1"> <strong>Please Select the Number of PDFs to Merge:</strong> </label> <select class="form-control" id="exampleFormControlSelect1"> <option name=" ...

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

Received the item back from the database query

When I run the code below; var results = await Promise.all([ database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTERVAL 1 DAY;"), database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTER ...

A PHP warning message has been triggered, indicating that the `strpos()` function expects the first parameter to be a string

WordPress Website Attention: AH01071: Error Encountered 'PHP message: PHP Warning: strpos() expects parameter 1 to be string, array given in /var/www/vhosts/mysite.com/httpdocs/wp-includes/functions.php on line 4102\nPHP message: PHP Warning: s ...

The issue of character encoding complications in JSON data formats

Whenever I convert an array to JSON, it displays "u00e1" instead of the proper character á. Is there a way to fix this issue with character encoding? Thank you ...

What is the best way to utilize regex for replacing a string within Node.js environment?

I'm struggling with updating the string in my code. Essentially, I have a .php file and I want to modify some constants using the replace package. The output of my current code is: // Current Output define('DB_NAME', 'foo'); // ...

history.js - failure to save the first page in browsing history

I have implemented the history.js library to enable backward and forward browser navigation on an AJAX products page triggered by clicking on product categories. While I have managed to get this functionality working smoothly, I am facing a particular iss ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

Yajl::ParseError: error in parsing: unrecognized character found in JSON data

Encountering an error while parsing with YAJL Ruby: 2.0.0-p0 :048 > Yajl::Parser.parse "#{resp.body}" Yajl::ParseError: lexical error: invalid char in json text. {"id"=>2126244, "name"=>"bootstrap", ...

Letters appear randomly at the conclusion of my phrase?

void splitWord(char phrase[]) { int len, len2, half; char firstHalf[BUF], secondHalf[BUF]; len = strlen(phrase); len2 = len / 2; len -= len2; strncpy(firstHalf, phrase, len-1); strncpy(secondHalf, (phrase + len), len2-1); ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

Problem with accessing state in React 16

In my code snippet below, I am encountering an issue. When the button is clicked and 'streaming' appears on the UI, the console.log within the 'process' function displays false. Can you help me identify what might be causing this discre ...