Tips for locating the differences between object keys nested within an array

Imagine having 3 objects, each with a "cost" key that contains an array of objects. The goal is to create a new object called "main" where the "value" in each item will be the difference between its value and the values of other objects.

const main = {
  cost: [
    { id: 'main', value: 20, timestapm: 'asd', current: '10'},
    { id: 'main', value: 10, timestapm: 'asd', current: '10'},
    { id: 'main', value: 18, timestapm: 'asd', current: '10'},
  ],
  description: 'maindevice',
  total: 5
}

const other = {
  cost: [
    { id: 'device1', value: 10, timestapm: 'qwe', current: '10'},
    { id: 'device1', value: 5, timestapm: 'qwe', current: '10'},
    { id: 'device1', value: 9, timestapm: 'qwe', current: '10'},
  ],
  description: 'maindevice',
  total: 3
}

const other2 = {
  cost: [
    { id: 'device2', value: 5, timestapm: 'zxc', current: '10'},
    { id: 'device2', value: 2, timestapm: 'zxc', current: '10'},
    { id: 'device2', value: 2, timestapm: 'zxc', current: '10'},
  ],
  description: 'maindevice',
  total: 6
}

const devices = [main, other, other2];

desired result:

main = {
  cost: [
    { id: 'main', value: 5, timestapm: 'asd', current: '10'},
    { id: 'main', value: 3, timestapm: 'asd', current: '10'},
    { id: 'main', value: 7, timestapm: 'asd', current: '10'},
  ],
  description: 'maindevice',
  total: 5
}

Answer №1

function updateCost(mainObj, obj1, obj2) {
    mainObj.cost = mainObj.cost.map((element, index) => { return {...element, value: obj1.cost[index].value - obj2.cost[index].value}})
    return mainObj
}

Give this function a try!

Answer №2

To optimize the code, you can iterate through the 'devices' array and update the values of the first object.

const
    main = { cost: [{ id: 'main', value: 20, timestamp: 'asd', current: '10'}, { id: 'main', value: 10, timestapm: 'asd', current: '10'}, { id: 'main', value: 18, timestapm: 'asd', current: '10'}], description: 'maindevice', total: 5 },
    other = { cost: [{ id: 'device1', value: 10, timestamp: 'qwe', current: '10'}, { id: 'device1', value: 5, timestapm: 'qwe', current: '10'}, { id: 'device1', value: 9, timestapm: 'qwe', current: '10'}], description: 'maindevice', total: 3 },
    other2 = { cost: [{ id: 'device2', value: 5, timestamp: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}, { id: 'device2', value: 2, timestapm: 'zxc', current: '10'}], description: 'maindevice', total: 6 },
    devices = [main, other, other2];

devices.reduce((r, o) => {
    o.cost.forEach(({ value }, i) => r.cost[i].value -= value);
    return r;
});

console.log(main);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 hide only the rows in a table when it is clicked using JavaScript?

Is there a way to hide rows in these tables by clicking on the table head? I'm currently using bootstrap 5 so JQuery is not an option. <table class="table table-info table-bordered"> <thead id="tablea"> ...

Deactivate a link within a specific element depending on the content of another element

I have a table with multiple rows. One column contains links (column a) and the other column displays either "Yes" or "No" (column b). If a cell in column b shows "No", I want to disable the link in the cell directly to its left in column a. I am using t ...

Adding a new item into an array of strings

I have a string with n elements. I need to add an automatically incremented number to the beginning of each line. For example: Data 66,45,34,23,39,83 64,46,332,73,39,33 54,76,32,23,96,42 I am splitting the string into an array using ',' ...

Freeing up memory allocated for JavaScript objects

Do I need to manually free allocated memory, or does JavaScript have a garbage collector? Is it acceptable to use this code snippet in JavaScript? function fillArray() { var c = new Array; c.push(3); c.push(2); return c; } var arr = fillArray(); ...

Having numerous profiles open could lead to ultimately controlling just one - selenium

I'm developing a unique application that empowers users to automate a process across multiple chrome profiles simultaneously. However, I am encountering an issue where the actions performed on each profile are only affecting one. Within my main scrip ...

The specified file for import cannot be located or is unable to be read: node_modules/bootstrap/scss/functions

I am currently using core UI version 2.1.1 along with react. Upon attempting to execute npm start, I encountered the following error: (/Users/umairsaleem/Desktop/abc/abc/node_modules/css-loader??ref--6-oneOf-5-1!/Users/umairsaleem/Desktop/abc/abc/node_mo ...

Unable to get onChange function to work with multiple input fields in React

I am attempting to implement a feature where an additional input field is added when the user clicks on the "Add input" button, and then store those input values in an object: const {useState } = React; const InviteUser = () => { const [userDetail ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Incorrect script enqueue order in child theme of WordPress

Help needed with enqueuing a script in a WordPress child theme. Despite specifying Jquery dependency, the script is loaded before Jquery. The code in question: add_action( 'wp_enqueue_scripts', 'child_theme_scripts' ); function child_ ...

create a promise type for a function in TypeScript

I came across this code recently and I'm curious about why it specifies the return type as Promise. Since the function is returning data, which is an object, what's the purpose of adding | null at the end? const getSomething = async ( id: stri ...

What steps can I take to stop a default route from adding headers to a particular route in Express.js?

Below are my Express.js route definitions: // Defining specific routes from a route file routes.use(this.initialize.bind(this)); routes.use(this.isAuthenticated.bind(this)); routes.use(this.isAuthorized.bind(this)); if (Route.METHOD == 'POST') { ...

error in memory allocation due to improper use of pointers and functions

Hey everyone, I wanted to share my code with you: #include <stdio.h> #include <stdlib.h> int power(int a, int b) { int exponent = b, result = 1; while (exponent != 0) { result = result * a; exponent--; } //prin ...

Adding elements to a multi-dimensional array using Array.push method may not yield the expected results

Looking to enhance a two-dimensional array in Ruby by adding more elements, but encountering issues with the .push method. After printing out all the elements and seeing the final line of the array, it's clear that something isn't right. Check o ...

What is the quickest method to set multiple positions in an array to zero?

I am seeking a more efficient way to assign zeros to all positions within a specified range in an array (specifically, positions 10 to 24). Currently, I am using the following method: ulong st[25]; ... for(int i = 10; i < 25; ++i) st[i] = 0x00UL; I am ...

Developing a custom sorting function for a React table using JSX

Struggling to find a solution to sort the rows array based on the sortBy and order state. Currently, I have a handleSort function that captures the column name and updates the sortBy state while toggling the order between "asc" and "desc". Now, I'm lo ...

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

What is the best way to recycle or invoke a function in Angular from a different file?

I have a function in file1.ts that acts as a converter. I am looking to reuse this function in file2.ts. Any suggestions or ideas? Thank you! #Code formatBytes(bytes, decimals = 2) : string | number { console.log("lol") if (bytes === 0) { r ...

Using regular expressions to replace a part of a jQuery file name

I'm working with a string that has a specific pattern, and I need to dynamically update the first digits in the file name within this string. For example: var newNumber = '123'; Transform this var str = '/folder1/folder2/folder3/567 ...

Authentication error: The API data retrieval was disrupted due to an unexpected termination of input

I encountered an error while trying to fetch data from an API using JavaScript. <button onclick="event.preventDefault(); getOdds()">Print odds</button> JS function getOdds() { const sportsKey = prompt("Enter the sports key:&q ...

What is the best way to activate an input field in react-select?

Currently, I am working on a dropdown feature using react-select and have encountered some issues that need to be addressed: 1) The input field should be focused in just one click (currently it requires 2 clicks). 2) When the dropdown is opened and a cha ...