Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array.

Here is the array:

[{ name: "Computer", name: "Car", name: "House", name: "Flower"}]

And here is the existing object:

{ computer: { title: 'Computer', color: 'Black' }, house: { title: 'House', color: 'Red' }}

To achieve this, the new object would look like:

{ computer: { title: 'Computer', color: 'Black' }, car: { title: 'Car', color:'' }, house: { title: 'House', color: 'Red' }, flower: { title: 'Flower', color:'' } } 

What is the best way to do this? One approach could be to loop through the array, compare the values, and extract the unique ones. However, I am unsure how to implement this effectively.

Answer №1

Based on my interpretation, it seems like the initial array is intended to consist of individual objects with a key named 'name', similar to the structure of the arr array.

const arr = [ {name: "Laptop"}, {name: "Tablet"}, {name: "Phone"}];
const objVal = { 
        laptop: { description: 'Laptop', color: 'Silver' }, 
        phone: { description: 'Phone', color: 'Black' }
        };
const expected = { 
        laptop: { description: 'Laptop', color: 'Silver' }, 
        tablet: { description: 'Tablet', color:'' },
        phone: { description: 'Phone', color: 'Black' } 
        } 

let resultObj = {};

arr.forEach((item) => {
    const itemDesc = item.name;
    if (objVal[itemDesc.toLowerCase()]) {
        resultObj[itemDesc.toLowerCase()] = objVal[itemDesc.toLowerCase()];
    } else {
      resultObj[itemDesc.toLowerCase()] = {
        description: itemDesc,
        color: ''
      }
    }
});

console.log(resultObj);

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

How to retrieve HTML attribute using D3 techniques

Looking to iterate through all rect nodes in the code snippet below: d3.selectAll("svg g rect") .on('mouseover', function (d) { console.log(this); }); When Console.log is executed, the following is printed: <rect class="cls" na ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

Effortless gliding towards the left

I am looking to incorporate buttons for smooth horizontal scrolling within my container. Currently, the functionality is in place but I would like to enhance its smoothness. How can I improve the scrolling experience? Should I consider using a different p ...

Tallying the Number of Accordion Toggle Clicks

Let me present a scenario where I have some accordions and would like to keep track of how many times the user expands each one. Could you guide me on how to implement this particular feature? Appreciate your support, Kevin ...

Personalize your Laravel collection

When dealing with an array structured like this, my goal is to organize the data in a specific manner. array:5 [ 0 => array:4 [ "message" => "Message number 1 for first conversation" "is_seen" => 0 "user_id" => 2 ...

The three.js raycaster is able to detect objects both in front of and behind the specific object I am trying to select

I am currently working on rendering a 3D model of a house using Three.js and encountering an issue with the raycaster in my code. The problem I'm facing is that it's selecting every object both behind and in front of the specific object I want to ...

A-Frame VR: Image missing from display on Chrome browser

UPDATE: I discovered that the issue was caused by running the HTML file from my local hard drive instead of a web server. Once I uploaded it to my web server and ran it from there, everything worked perfectly. A-Frame Version: 0.4.0, Chrome: 55.0.2883.87, ...

What factors may be influencing the incorrect behavior of this simple code when using useState()?

In an attempt to replicate a problem I encountered in a larger project component, I have created a simple component. Let's consider the scenario where we have an arrayA and we want to add the value 1 to it on each button click, while also updating ano ...

The click function for the responsive navbar hamburger is not functioning properly

Having some trouble with the code not working in responsive mode. I've tested it on a 600px screen and the hamburger button doesn't seem to work (I click it and nothing happens). I've gone through both the CSS and JS multiple times but can&a ...

navigation bar: retain link hover state even after displaying sub-menu

My navigation bar has submenus with background images in .png format. Only 3 links in my navbar have these submenus. The issue I am facing is that when the menu link is in a hover state and the submenu is being hovered over, the nav link loses its hover st ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

A script in PHP or JavaScript that dynamically generates two dual drop-down menus to assist with data selection

I have experience with php scripting, but I am facing challenges when trying to combine it with JavaScript. The issue arises when I have a form that includes dropdown menus for categories and subcategories. When a category is selected, the options in the s ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

Exploring jQuery AJAX and how to effectively manage various data types

ASP.Net MVC is the framework I am currently using, but this issue can apply to any framework out there. When making an Ajax call to my server, most of the time it returns plain HTML content. However, in case of an error, I want it to return a JSON object ...

Trouble with Bootstrap 5 Dropdown Menu failing to drop down

I am attempting to utilize a dropdown menu on my Wordpress site with Bootstrap, but it is not working as expected. If I manually add the class "show" to my dropdown-menu div, the menu displays, but the button does not function. These are the scripts being ...

Displaying gratitude message using AJAX and executing PHP script

I've created a form where I want the "thank you" message to be displayed after submission and also run a PHP script to insert data into the database. However, currently, although the values are being passed correctly via the URL, the upis.php script i ...

Refine the Crossfilter dimension according to the specified date range

What is the proper way to filter a date range using Crossfilter? The code above does not seem to yield any results, but I am certain that there are records within that specified time period. Var myDimension = CrossFilterObj.dimension(function(d) { retur ...

How can I turn off strict null checks in TypeScript when using ESLint?

ESLint keeps flagging my object as potentially null despite having an if statement to check for it. const user: User | null = getUser() if (user) { // if (user !== null) doesn't work either await user.updateProfile({ di ...

Struggling to retrieve an element from an object received through a get request in Express

I am facing an issue with a get request that returns an array of objects retrieved from a database using Knex. I am trying to use .map to make these objects accessible, but I am struggling with accessing the final element which is a sum(). It seems like a ...