Combine two entities to create a new entity that mirrors the structure of the first entity

Can someone assist me with a data structure issue?

Here are the objects I am working with:

const elements = {
  item1: {color: 'blue', name: 'Item One' },
  item2: {color: 'green', name: 'Item Two' },
  item3: {color: 'red', name: 'Item Three' },
}

const values = { id: 0, item1: 20, item2: 50, item3: 10 }

I am trying to create another object (elementsWithValues) in this format:

const elementsWithValues = {
  item1: {color: 'blue', name: 'Item One', value: 20 },
  item2: {color: 'green', name: 'Item Two', value: 50 },
  item3: {color: 'red', name: 'Item Three', value: 10 },
}

This is the code snippet I have attempted:

const elementsWithValues = [
  ...Object.entries(elements).map(([itemName, element]) => ({
    [itemName]: { ...element, value: values[itemName] },
  })),
]

However, I am currently getting this result:

[
  { item1: {color: 'blue', name: 'Item One', value: 20 } },
  { item2: {color: 'green', name: 'Item Two', value: 50 } },
  { item3: {color: 'red', name: 'Item Three', value: 10 } },
]

Answer №1

Close, but the correct method to use here is reduce instead of map.

const data = {
  item1: {type: 'car', color: 'red' },
  item2: {type: 'bike', color: 'blue' },
  item3: {type: 'boat', color: 'green' },
}

const info = { id: 1, item1: 'Toyota', item2: 'Yamaha', item3: 'Speedboat' }

const updatedInfo = Object.entries(data).reduce((obj,[itemName, details]) => {
    obj[itemName] = { ...details, newInfo: info[itemName] };
    return obj;
 }, {})

console.log(updatedInfo)

Answer №2

To bring an object back from entries, follow this code snippet.

Object.fromEntries(Object.entries(dataInfo).map(([k, val]) => [k, { ...val,
  val: newDataPoint[k]
}]))

const dataInfo = {
  categoryA: {
    color: 'purple',
    name: 'Category Alpha'
  },
  categoryB: {
    color: 'orange',
    name: 'Category Beta'
  },
  categoryC: {
    color: 'blue',
    name: 'Category Charlie'
  },
}

const newDataPoint = {
  id: 0,
  categoryA: 12,
  categoryB: 45,
  categoryC: 78
}

const updatedResult = Object.fromEntries(Object.entries(dataInfo).map(([k, val]) => [k, { ...val,
  val: newDataPoint[k]
}]))

console.log(JSON.stringify(updatedResult))

Answer №3

I prefer breaking it down into two steps for better code readability. First, copying the infos and then updating the values:

const infos = {
  columnA: {color: 'red', name: 'Column Ancient' },
  columnB: {color: 'yellow', name: 'Column Blue' },
  columnC: {color: 'green', name: 'Column Consequence' },
}

const datum = { id: 0, columnA: 5, columnB: 100, columnC: 33 }

// begin the logic here!
infosWithValues = { ...infos }; // make a copy
Object.keys(infosWithValues)
      .forEach(k => infosWithValues[k].value = datum[k]); // update the values

console.log(infosWithValues);

Answer №4

Getting the desired result is quite simple - you can achieve it by spreading your array of objects within a call to Object.assign() as shown below:

const infos = {
  columnA: {color: 'red', name: 'Column Ancient' },
  columnB: {color: 'yellow', name: 'Column Blue' },
  columnC: {color: 'green', name: 'Column Consequence' },
};

const datum = { id: 0, columnA: 5, columnB: 100, columnC: 33 };
const infosWithValues = Object.assign({}, 
  ...Object.entries(infos).map(([columnName, info]) => ({
    [columnName]: { ...info, value: datum[columnName] },
  })),
);

console.log(infosWithValues);

Alternatively, you can utilize the newer Object.fromEntries() method. This method takes an array of [[key, value], ...] pairs and constructs an object from that array:

const infos = {
  columnA: {color: 'red', name: 'Column Ancient' },
  columnB: {color: 'yellow', name: 'Column Blue' },
  columnC: {color: 'green', name: 'Column Consequence' },
};

const datum = { id: 0, columnA: 5, columnB: 100, columnC: 33 };
const infosWithValues = Object.fromEntries(
  Object.entries(infos).map(([columnName, info]) => 
    [columnName, { ...info, value: datum[columnName] }]
  )
);

console.log(infosWithValues);

Answer №5

let data = {
  firstItem: {color: 'blue', name: 'First Object' },
  secondItem: {color: 'green', name: 'Second Object' },
  thirdItem: {color: 'red', name: 'Third Object' },
}

let values = { id: 1, firstItem: 10, secondItem: 50, thirdItem: 25 }

let dataWithValues = Object.assign({}, data);

Object.keys(values).forEach(key => {
  if (dataWithValues[key]) dataWithValues[key].value = values[key];
});

console.log(dataWithValues);

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 include temporary attributes on a mongoose object solely for the purpose of a response, without saving them to the database

I am looking to add extra temporary properties with additional data to the response but have encountered some difficulties. 'use strict'; var mongoose = require('mongoose'); var express = require('express'); var app = expres ...

Turn off laptop camera to assess web application functionality in the absence of a camera on the device

In the process of creating an automated testing framework in Java and Selenium, I have encountered a scenario where I need to examine how a web application behaves when accessed by a user with a device lacking a camera. Is there a method to simulate this ...

Adding date restrictions to the main method is necessary for controlling the input and output

I have a function in my react-native package that requires "from" and "to" dates as parameters. I need to implement a rule that ensures the "to" date is always after the "from" date. Where should I insert this requirement in the following code snippe ...

How to update an empty array in NodeJS using Mongoose

I am currently in the process of developing a NodeJS application that generates reports based on data from a Microsoft SQL database. All the relevant data for the application is stored in a MongoDB database using Mongoose. Within my Mongoose model, I have ...

How can I access the id_lang variable in React JS from outside its scope?

How do I access the 'id_lang' variable outside of the render function in order to pass it down for checking? const Navbar = () => { const getID = async (id) => { let id_lang = id; console.log(id_lang); } ret ...

Tips for sending a JavaScript variable through an AJAX URL

I currently have a variable defined like this: var myip; I need to include this variable in the following URL: $.ajax('http://api.ipstack.com/**[myip]**?access_key=mykey') Manually replacing [myip] with my IP address works fine, but I am loo ...

Is there a way to efficiently include numerous jQuery scripts in a batch process, each with a slight variation, using a loop?

Currently, I have a script that calculates the blur effect for multiple images based on the mouse position and scroll position. However, I am looking for a more efficient way to apply this to around 100 images without duplicating the script each time. var ...

Accessing a Kendo Grid instance within an Angular directive

Continuing from the previous question, which can be found here, I have an additional query that I felt warranted a separate post. The link provided above demonstrates how to obtain a grid instance in Angular, credit to Lars for that. Building upon the ex ...

Animate elements in Vue.js when navigating between pages is a great way to enhance user

I'm looking to add animation to a specific element once the route page finishes loading. This is not related to route page transitions. I've experimented with various methods, trying to animate a progress bar based on dynamic data values. I attem ...

How to access a deeply nested object in Angular 2

I am currently grappling with the challenge of extracting information from an object in a JSON response. The structure of the data is shown below: {"bpi":{"2017-10-03":4320.09,"2017-10-04":4225.9238,"2017-10-05":4322.755,"2017-10-06":4370.245,"2017-10-0 ...

Clicking on a flex card will trigger the opening of a new page where the parsed data will be displayed in a stylish manner using JavaScript

Currently, I am attempting to showcase the data retrieved from the following URL: . My objective is to format the parsed data with a specific style. However, I have encountered difficulties accomplishing this using `window.open()`. Any assistance in resolv ...

What steps can I take to avoid Vue.js overriding jQuery bindings within components?

After incorporating vue.js into an existing project and attaching the vue instance to the body tag with an ID of "app," everything seemed to be running smoothly. jQuery and Vue.js were cooperating well together. However, as soon as I started creating compo ...

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...

Which language is better for refreshing web pages: PHP or Javascript?

May I seek your opinion on this matter? I have the ability to refresh my page using two different methods, but I am uncertain of any potential drawbacks. Can you advise me on which one I should utilize? Edit: Specifically, I am referring to the use of he ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

Automatically populate the article number field once the article name has been entered

I am currently working on a HTML <form> using PHP. Within this form, there are three <input> fields. The goal is to have the second <input> field automatically populate once the first one is filled out. This will involve triggering an HTT ...

Displaying live data from a spreadsheet directly on a sidebar

My goal is to extract data from another sheet in the same spreadsheet and present it as a dropdown selection in the sidebar. The code.gs file contains a function called getVisualData() that successfully retrieves the desired list: function getVisualData() ...

Speedily deliver a message to the designated destination

I have a specific route set up at /test: app.route('/test', (req,res)=>{ res.sendFile(__dirname + "\\myhtml.html") }) Now, I want to trigger an event in Node.js on the /test route, and have myhtml.html file listen for ...

The checkbox linked to a Vector layer in Openlayers 3 seems to have no effect on its visibility

Help me debug my code where I am attempting to connect a checkbox to a vector layer's 'visible' property. I can't seem to figure out what's wrong, can you spot the error? Interestingly, this code successfully works for ol.layer.Ti ...

Is it possible to navigate to the Next page using a different button instead of the pagination controls

Is it possible to navigate to the next page upon clicking a button labeled "Press me"? Here is the code snippet: <!doctype html> <html ng-app="plunker"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/an ...